Javascript将函数绑定到对象
为什么这样不行<代码>人物仍然拥有原始属性“Mike”和“New Zealand”。为什么不Javascript将函数绑定到对象,javascript,Javascript,为什么这样不行人物仍然拥有原始属性“Mike”和“New Zealand”。为什么不personUpdate.bind(person)我想这样做,每次调用personUpdate这个引用person对象(并且不使用new)。调用.bind不会修改传入的函数;它返回一个新的绑定函数 因此,您希望: const person = { name: "Mike", country: "New Zealand" } function personUpdate(name, country)
personUpdate.bind(person)
我想这样做,每次调用personUpdate
这个引用person
对象(并且不使用new
)。调用.bind
不会修改传入的函数;它返回一个新的绑定函数
因此,您希望:
const person = {
name: "Mike",
country: "New Zealand"
}
function personUpdate(name, country) {
this.name = name
this.country = country
}
personUpdate.bind(person)
personUpdate('Tony', 'Chile')
或:
调用.bind
不会修改传入的函数;它返回一个新的绑定函数
因此,您希望:
const person = {
name: "Mike",
country: "New Zealand"
}
function personUpdate(name, country) {
this.name = name
this.country = country
}
personUpdate.bind(person)
personUpdate('Tony', 'Chile')
或:
我已经试过你的代码,我认为没有什么问题
personUpdate = personUpdate.bind(person); // overwrite the original function
我试图打印它,但它给了我“Tony”和“Chile”,或者我误解了你的问题?我试过你的代码,我认为它没有问题
personUpdate = personUpdate.bind(person); // overwrite the original function
我试图打印它,但它给了我“Tony”和“Chile”,或者我误解了你的问题?var boundPersonUpdate=personUpdate.bind(person);边界更新(“托尼”、“智利”);var boundPersonUpdate=personUpdate.bind(person);边界更新(“托尼”、“智利”);