nodejs异步回调函数中this问题,求助
发布于 8 年前 作者 suntopo 5160 次浏览 来自 问答
var val1 = 'hello me';
function test() {
    var val1 = 'hello he';
    fs.readFile(path.join(__dirname, '/test.js'), function(err, data){
        var val1 = 'hello you' +
            '';
        console.log(this.val1);
        console.log(this === GLOBAL);
    });
}

test();

console.log

undefined true

为啥子?

求问下this为什么是全局对象?

异步回调函数中的上下文是怎么确定的?

3 回复

this关键字指向调用它的对象,test()是在GLOBAL中调用,而且异步函数回调应该形成了闭包,回调函数中的this也应该指向GLOBAL对象,而至于为啥this.vall是undefined,则是因为用var申明的变量都是局部变量,并不是GLOBAL变量的属性。

function test(){
    var that = this;
    var fs = require("fs");
    fs.readFile(__dirname + "/test.js", function(err, data){
        console.log(that.vall);
        console.log(this === GLOBAL);
    });
};
var scope = {vall : 'hehe'};
test.apply(scope,[]);

这段代码中输出的应该是hehe和true。 楼主好好去看看javascript中this关键字指的对象和闭包的概念吧。希望能帮到你。

在这个例子中test作普通调用模式 即test()this指向全局 在node是GLOBAL 如果是作为方法调用 如 new Class().test() 那么this指向 new 出来的实力 如果是call apply 调用 this指向第一个参数 然后bind 也可以改变this 匿名函数的this都是全局 随便整理了一下 具体还是看规范吧 解决方法楼上说了 至于为什么console.log(this.val1); 输出的是undefined 因为 val1 不是挂在global上的 他只是node的一个模块中的一个变量而已 那么自然是没有的

@iyuq 而且异步函数回调应该形成了闭包 – 这一点正好是我不知道的地方

回到顶部