gpt4 book ai didi

javascript - JS通过2箭头函数this.push()

转载 作者:行者123 更新时间:2023-12-04 09:45:43 26 4
gpt4 key购买 nike

我对 JavaScript 中的词法绑定(bind)有疑问。
这是我的代码:

.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

但是当我使用像 function(url,enc,done){...} 这样的 es5 函数语法时:
.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() 与箭头函数一起使用?
我知道箭头函数的词法绑定(bind),但我不知道如何使用 this .

感谢您阅读我的文字。

最佳答案

那么在前一种情况下,您的 this指向window目的。这就是你收到错误的原因。
arrow函数不提供自己的this绑定(bind)(它们保留封闭词法上下文的 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 - JS通过2箭头函数this.push(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62127678/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com