2015-05-02 153 views
0
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秒后,两个变量都应设置为true,但只有tempOut更改。我做错了什么?JavaScript改变对象内部的变量

回答

1

你的代码改成这样:

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

你的“本”方面是不是在正确的目标指向,在一个浏览器,它引用的setTimeout内窗口。

看一看这个,范围是JS有点mindbending:http://ryanmorr.com/understanding-scope-and-context-in-javascript/

+1

'this',计时器内,指向'window'对象。 –

+1

加入了我的帖子。 – garryp

+0

非常感谢。我非常感谢你的帮助。 – Humberd