跳到主要内容
CNode

js作用域怎么理解?

社区
Xxingren23发布于 13 年前最后回复 13 年前
757220

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

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

查看回复

回复 (7)

R
ringtail#613 年前
引用 jayceefunfunction Foo() { this.value = 42; this.method = function () { console.log(this.value); }; setTim...

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

 var that = this;
 setTimeout(function () {
     that.doStuff();
 }, 4000);
X
xingren23#513 年前
引用 jayceefunfunction Foo() { this.value = 42; this.method = function () { console.log(this.value); }; setTim...

@ringtail

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

B
brighthas#413 年前
... ...

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

... ...

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

R
ringtail#313 年前
引用 jayceefunfunction Foo() { this.value = 42; this.method = function () { console.log(this.value); }; setTim...

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

X
xingren23#213 年前
引用 jayceefunfunction Foo() { this.value = 42; this.method = function () { console.log(this.value); }; setTim...

明白了,感谢~

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

J
jayceefun#113 年前

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

参与回复

登录后即可参与回复。登录