我在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的词法绑定,但是我不知道使用它。
感谢您阅读我的文字。
[在前一种情况下,您的this
指向window
对象。这就是为什么您会收到错误消息。