JavaScript - “this”的所有者 [英] JavaScript - Owner of "this"

查看:143
本文介绍了JavaScript - “this”的所有者的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我按照教程创建JavaScript秒表,并尝试展开它与多个秒表(一个类的多个实例)一起工作。我有问题是当我试图显示当前值,而时钟滴答声我需要硬代码类实例,因为使用这不工作(在我使用console.log的行)。我已经把代码下降到最小,试图理解这方面,并粘贴了我有以下:

I followed a tutorial for creating a JavaScript stopwatch and am trying to expand it to work with multiple stopwatches (multiple instances of a class). The problem I have is when I am trying to display the current value while the clock is ticking I need to hard code the class instance becasue using "this" doesn't work (on the line where I am using console.log). I have cut the code down to the minimum to try to understand this aspect, and have pasted what I have below:

function Timer(){
    var time1 = null;
    var time2 = null;
    var timeLoop = null;

    function getTime(){
        var day = new Date();
        return day.getTime();
    }

    this.start = function(){
        time1 = getTime();

        timeLoop = setInterval(function(){
            time2 = getTime();
            console.log(_Timer.duration());
            //console.log(this.duration());
        },500);
    }

    this.duration = function(){
        return (time1 - time2) / 1000;
    }

}       

我认为下面的链接描述了我的问题,但我不明白它足以应用它在这里。是问题是由于所有者是this.start而不只是这个,我怎么能修改代码,使其与任何Timer的实例一起工作?

I think the link below describes my problem but I don't understand it enough to apply it here. Is the issue due to the owner being this.start rather than just this and how can I ammend the code to make it work with any instance of Timer?

http://www.quirksmode.org/js/this.html

我已经包括硬编码值行和this行不起作用。

I have included both the hard coded value line and the "this" line that doesn't work.

谢谢,

Geraint

推荐答案

如果你想拥有

If you want to have the this property be consistent, you should bind the functions that are being called.

例如,

setInterval(function(){/ * code here * /} .bind(this),500)

这样,内部函数的 this 将与外部函数的<$ p $ c>相同。

That way, the this of the inner function will be the same as that of the outer function.

这篇关于JavaScript - “this”的所有者的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆