js作用域怎么理解?
发布于 10 年前 作者 xingren23 4476 次浏览 最后一次编辑是 8 年前

代码执行为什么输出undefined(虽然作者注释了this指向全局对象,小白还是晕了。。。)?

function Foo() { this.value = 42; this.method = function() { // this 指向全局对象 console.log(this.value); // 输出:undefined }; setTimeout(this.method, 500); } new Foo();

7 回复

function Foo() { this.value = 42; this.method = function () { console.log(this.value); }; setTimeout(this.method(), 500); //42 } var foo = new Foo(); console.log(foo.value); //42 foo.method() //42

明白了,感谢~

this.method = function() { // this 指向全局对象,这里的this并不是 this.value中的this。 console.log(this.value); // 输出:undefined };

@xingren23 其实是这样的,setTimeout会将作用域变换为全局的,这是javascript的一个坑,你自己试一下,不管你怎么搞setTimeout()函数中只要引用this,那么一定是全局的.

... ...

setTimeout(obj.method.bind(obj), 500);

... ...

签名: 交流群244728015 《Node.js 服务器框架开发实战》 http://url.cn/Pn07N3

@ringtail

感谢,个人理解是因为setTimeout总是在全局环境中执行的,js的函数作用域永远不会生效,也就一定是全局的this了。

@xingren23 通常的这个位置的处理是这样的

 var that = this;
 setTimeout(function () {
     that.doStuff();
 }, 4000);

@ringtail 嗯,这样就完美了。

回到顶部