据我了解,当调用对象的方法时,该方法中的 this
值会分配给对象本身。
const dog = {
age: 5,
growOneYear: function () {
this.age += 1;
}
};
dog.growOneYear();
dog.age; // 6
这对我来说很有意义。但是,当我以不同的方式尝试时,它不起作用:
function invokeTwice(cb) {
cb();
cb();
}
invokeTwice(dog.growOneYear);
dog.age;
// still 6
为什么这不起作用?
最佳答案
在第二个示例中,没有用于调用growOneYear()
的对象。
将方法 growOneYear
复制到新变量 (cb
) 中。这会失去 dog
和 growOneYear
之间的联系。然后,您可以将 cb()
作为常规函数调用,而无需使用对象在方法内充当 this
。
您在问题中说:
... when invoking a method of an object, the
this
value in that method is assigned to the object itself.
上面的陈述是正确的,它解释了为什么当您调用 growOneYear
作为 cb()
时它不起作用:它只是“对象的方法”当它被作为 dog.growOneYear()
调用时。如果将其复制到 cb
中并将其调用为 cb()
,那么它只是一个常规函数;不再使用任何对象来调用它。
您在问题中描述的情况甚至在 Function.prototype.bind()
的文档中列出:
A common mistake for new JavaScript programmers is to extract a method from an object, then to later call that function and expect it to use the original object as its
this
(e.g. by using that method in callback-based code). Without special care, however, the original object is usually lost.
Function.prototype.bind()
是您问题的解决方案:
const dog = {
age: 5,
growOneYear: function () {
this.age += 1;
}
};
dog.growOneYear();
console.log(dog.age); // 6
function invokeTwice(cb) {
cb();
cb();
}
// Bind the method to the desired object
// Inside `invokeTwice()`, `cb` is the function `dog.growOneYear` with
// `this` pointing to `dog` ------+
// v
invokeTwice(dog.growOneYear.bind(dog));
console.log(dog.age); // 8
关于javascript - 该关键字的分配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53649524/