js作用域怎么理解?
发布于 12 年前 作者 xingren23 5496 次预览 最后一次回复是 12 年前 来自
代码执行为什么输出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,那么一定是全局的.
@ringtail
感谢,个人理解是因为setTimeout总是在全局环境中执行的,js的函数作用域永远不会生效,也就一定是全局的this了。
@xingren23 通常的这个位置的处理是这样的
@ringtail 嗯,这样就完美了。