我对 .bind() 函数有疑问。 我有这段代码,它输出 Window 对象,我不明白为什么。你能向我解释一下为什么bind(this)对函数没有影响吗?
let vakho = {
name: "salome",
a: function () {
let something = function () {
return this;
}
something.bind(this)
return {
f: function () {
return something();
}
}
},
}
console.log(vakho.a().f())
最佳答案
.bind
返回一个带有附加上下文的新函数。您需要再次将结果分配给something
。
let vakho = {
name: "salome",
a: function () {
let something = function () {
return this;
};
something = something.bind(this); // Assign to the something
return {
f: function () {
return something();
}
}
},
}
console.log(vakho.a().f());
console.log(vakho.a().f().name);
关于javascript - 为什么 bind() 不适用于对象内部另一个函数内的函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47672780/