更新原型变量Javascript

时间:2012-07-04 11:03:16

标签: javascript oop prototype

我正在开展一个项目,我需要通过方法video.prototype.getCurrentFrame()从播放视频中返回一个framecount。我的脚本工作得非常好,因为这个方法返回的数字是'undefined'。我知道我的问题必须与我的变量范围有关,但我是javascript的新手,我似乎无法让它自己工作......

在我的方法video.prototype.setUpPlayer中,我有一个函数,允许我计算framcount 'timeListener',我更新一个名为frame的变量; 如果我尝试通过video.prototype.getCurrentFrame()访问此帧变量,则它不会达到更新的值。

到目前为止,这是我的代码:

var Video = function(aVideoId){
this.videoId = aVideoId;
this.frame;
this.videoContainer; 
this.myPlayer;
this.timeListener;
this.progressListener;
};

Video.prototype.getCurrentFrame = function(){
    return this.frame;
}

Video.prototype.setVideoContainer = function(){
        videoContainer = $('<div>', {
        id: this.videoId,
        class: 'projekktor',
        width: "100%",
        height: "100%",
    });
    $('#innerContainer').html(videoContainer);
}

Video.prototype.setUpPlayer = function(){
    videoId = this.videoId;


    myPlayer = projekktor('#' + videoId, {
        controls: "true",
        volume: 0.5,
        preload: false,
        autoplay: true,
        playlist: [{
            0: {
                src: '/' + videoId + '.mp4',
                type: 'video/mp4'
            },
            1: {
                src: '/' + videoId + '.mov',
                type: 'video/mov'
            },
            2: {
                src: '/' + videoId + '.ogv',
                type: 'video/ogv'
            }
        }]
    }, function() { // call back
        myPlayer.addListener('time', timeListener);
        myPlayer.addListener('progress', progressListener);
    });

    timeListener = function(duration) {
            $('#currentTime').html(duration);
            frame = Math.round(duration * 25);
            $('#currentFrame').html(frame); 
                            return this.frame = frame;


        }

    progressListener = function(value) {
            $('#progress').html(Math.round(value))
            $('#progress2').html(myPlayer.getLoadProgress());
        }   
}

提前感谢您的帮助!

1 个答案:

答案 0 :(得分:2)

您需要从getCurrentFrame的实例调用Video,而不是原型本身:

var video = new Video;
alert(video.getCurrentFrame());

使用原型检索当前帧的唯一方法是使用apply()(这也需要一个实例):

var video = new Video;
alert(Video.prototype.getCurrentFrame.apply(video));

编辑:似乎timeListener回调未在视频实例的上下文中执行。您可能必须显式绑定回调到正确的范围:

timeListener = function() 
    {
    //  ...
        this.frame = frame;
    //  ...
    }

var video = new Video;

// binding the correct context
myPlayer.addListener('time', timeListener.bind(video));
this关闭中的

timeListener现在为video