2017-07-04 49 views
0
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)我想使它,以便personUpdatethis的每个电话都参照person对象(并且不使用new)。对对象的Javacript绑定功能

+1

var boundPersonUpdate = personUpdate.bind(person); boundPersonUpdate('Tony','Chile'); – kangsu

回答

2

调用.bind不会修改您传入的函数;它返回一个新的绑定函数。

所以,你想要么:

var boundPersonUpdate = personUpdate.bind(person); 
boundPersonUpdate(...); // call the bound version 

或:

personUpdate = personUpdate.bind(person); // overwrite the original function 
0

我曾尝试你的代码,我认为没有什么不妥的地方。

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'); 

我试图打印它,它给我“托尼”和“智利”,或者我误解了你的问题?