const person = {
name: "Mike",
country: "New Zealand"
}
function personUpdate(name, country) {
this.name = name
this.country = country
}
personUpdate.bind(person)
personUpdate('Tony', 'Chile')
为什么这个不起作用?person
仍然有原始的属性‘迈克’和‘新西兰’。为什么不这样做呢?我想让每次调用personUpdate.bind(person)
personUpdate
时,this
都会引用person
对象(而不使用new
)。
发布于 2017-07-04 09:50:51
调用.bind
不会修改您传入的函数;它会返回一个新的绑定函数。
所以你想要哪一个:
var boundPersonUpdate = personUpdate.bind(person);
boundPersonUpdate(...); // call the bound version
或者:
personUpdate = personUpdate.bind(person); // overwrite the original function
发布于 2017-07-04 10:05:12
我已经试过你的代码了,我想它没什么问题。
const person = {
name: "Mike",
country: "New Zealand"
}
function personUpdate(name, country) {
this.name = name;
this.country = country;
console.log(this.name);
console.log(this.country);
}
personUpdate.bind(person);
personUpdate('Tony', 'Chile');
我试着打印它,它给了我“托尼”和“智利”,还是我误解了你的问题?
https://stackoverflow.com/questions/44895792
复制相似问题