JS通过2箭头函数this.push()
JS through2 Arrow function this.push()
我在 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
但是当我使用 es5 函数语法时 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() 与箭头函数一起使用?
我知道箭头函数的词法绑定,但我不知道如何使用 this
.
感谢阅读我的文字。
在前一种情况下,您的 this
指向 window
对象。这就是您收到错误的原因。
arrow
函数不提供它们自己的 this
绑定(它们保留封闭词法上下文的 this 值)
In arrow functions, this retains the value of the enclosing lexical
context's this. In global code, it will be set to the global object:
var globalObject = this; var foo = (() => this); console.log(foo() ===
globalObject); // true
检查一下 MDN-this 特别是 箭头函数 部分
我在 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
但是当我使用 es5 函数语法时 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() 与箭头函数一起使用?
我知道箭头函数的词法绑定,但我不知道如何使用 this
.
感谢阅读我的文字。
在前一种情况下,您的 this
指向 window
对象。这就是您收到错误的原因。
arrow
函数不提供它们自己的 this
绑定(它们保留封闭词法上下文的 this 值)
In arrow functions, this retains the value of the enclosing lexical context's this. In global code, it will be set to the global object:
var globalObject = this; var foo = (() => this); console.log(foo() === globalObject); // true
检查一下 MDN-this 特别是 箭头函数 部分