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

Warum funktioniert das nicht? person hat immer noch die Originaleigenschaften 'Mike' und 'New Zealand'. Warum nicht personUpdate.bind(person) Ich möchte es so machen, dass jeder Anruf an personUpdate die this bezieht sich auf das person Objekt (und ohne new verwenden).JavaScript-Bindungsfunktion an ein Objekt

+1

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

Antwort

2

Durch den Aufruf .bind wird die übergebene Funktion nicht geändert. Es gibt eine neue gebundene Funktion zurück.

So möchten Sie entweder:

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

oder:

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

Ich habe Ihren Code versucht, und ich denke, nichts mit ihm nicht stimmt.

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

Ich habe versucht, es zu drucken und es gibt mir "Tony" und "Chile", oder ich missverstanden Ihre Frage?

Verwandte Themen