我正在阅读this page只是为了温习 .apply
语法,我意识到我的 JS 知识存在差距:
您可以使用 .bind
和 .apply
更改函数中 this
的值(我假设 .call
遵循与 .apply
相同的规则,所以我不会单独谈论它)。所以我想知道,如果我使用 .bind
然后用 .apply
调用它,哪个会优先?
所以我只是从 w3schools 中引用了示例并对其进行了修改:
var person = {
fullName: function(city, country) {
return this.firstName + " " + this.lastName + "," + city + "," + country;
}
}
var person1 = {
firstName: "John",
lastName: "Doe"
}
var person2 = {
firstName: "Mary",
lastName: "Anne"
}
fn = person.fullName.bind(person2);
console.log(fn.apply(person1, ["Oslo", "Norway"]));
因此,如果它打印 Mary Anne,则 .bind
给出的 this
值优先于 .apply
给出的值。
确实如此!玛丽·安妮被打印了。所以这让我想知道是否还有其他我不太理解的关于this
的规则。例如,调用.bind
后可以重新绑定(bind)吗?
最佳答案
.bind
返回一个绑定(bind)函数。 绑定(bind)函数和箭头函数永远不会再次更改其上下文,因此您无法重新.bind
它们或.apply
另一个上下文。
如果我们假设 .bind
是用 JavaScript 本身编写的,那么情况可能会变得更清楚……那么它会写成:
function bind(context, ...args) {
const fn = this;
return function(...args2) {
// Note: "this" does not get accessed inside this function, so .bind ing it or .apply ing another context doesnt change anything
return fn.call(context, ...args, ...args2);
}
}
关于javascript - 覆盖 .bind 和 .apply 中的 `this`,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56296469/