JS through2箭头函数this.push()

问题描述 投票:0回答:1

我在JavaScript中遇到关于词法绑定的问题。我的代码是

.pipe(through.obj((url, enc, done)=>{
        if(!url) return done();
        request.head(url, (err, response)=>{
            this.push(url + ' is ' + (err ? 'down' : 'up') + '\n');
            done();
        });
    }))

那么结果是

TypeError: this.push is not a function

但是当我用函数(url,enc,done){...}定义转换函数时,像这样

.pipe(through.obj(function(url, enc, done){
        if(!url) return done();
        request.head(url, (err, response)=>{
            this.push(url + ' is ' + (err ? 'down' : 'up') + '\n');
            done();
        });
    }))

然后我的代码运行良好。

在这种情况下,我如何通过箭头功能使用this.push()?我知道Arrow Function的词法绑定,但是我不知道使用它。

感谢您阅读我的文字。

javascript arrow-functions lexical-scope
1个回答
0
投票

[在前一种情况下,您的this指向window对象。这就是为什么您会收到错误消息。

© www.soinside.com 2019 - 2024. All rights reserved.