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

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

问题描述

我遵循了教程来创建 JavaScript 秒表,并且正在尝试扩展它可以与多个秒表(一个类的多个实例)一起使用.我遇到的问题是,当我试图在时钟滴答作响时显示当前值时,我需要对类实例进行硬编码,因为使用this"不起作用(在我使用 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 而不仅仅是 this,我该如何修改代码以使其适用于任何 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.

谢谢,

杰兰特

推荐答案

如果你想让 this 属性保持一致,你应该绑定被调用的函数.

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将与外部函数的this相同.

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

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

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