2017-07-04 53 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'); 

我試圖打印它,它給我「託尼」和「智利」,或者我誤解了你的問題?