JavaScript 更改对象内的变量

JavaScript changing variables inside an object

var tempOut = false;
var foo = function () {
    this.tempIn = false;

    this.counter = function () {
        setTimeout(function () {
            this.tempIn = true;
            tempOut = true;
        },5000);
    };
};

var myFunction = new foo();
myFunction.counter();
console.log(tempOut+ " " + myFunction.tempIn);

嘿,我有一个简单的代码可以在 5 秒后更改变量。 有 2 个变量:一个全局变量 (tempOut) 和一个局部变量 (tempIn)。当我从函数 foo 创建对象并在 5 秒后启动 counter 函数时,两个变量都应设置为 true,但只有 tempOut 变化。我做错了什么?

将您的代码更改为:

var foo = function () {
    this.tempIn = false;
    var me = this;
    this.counter = function () {
        setTimeout(function () {
            me.tempIn = true;
            tempOut = true;
        },5000);
    };
};

您的 "this" 上下文未指向正确的对象,在浏览器中它在 setTimeout 中引用 window。

看看这个,范围在 JS 中有点令人费解:http://ryanmorr.com/understanding-scope-and-context-in-javascript/