CNode

js作用域怎么理解?

Xxingren23发布于13 年前最后回复13 年前7 回复5695 浏览0 收藏

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

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

查看回复

回复 (7)

J
jayceefun#1·13 年前

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

X
xingren23#2·13 年前
引用 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 };

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

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

B
brighthas#4·13 年前
... ...

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

... ...

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

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

@ringtail

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

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

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

 var that = this;
 setTimeout(function () {
     that.doStuff();
 }, 4000);
参与回复
登录后即可参与回复。登录