我發現這個示例代碼:「this」如何在構造函數中分配的函數中工作?
function personFullName() {
return this.first + ' ' + this.last;
}
function Person(first, last) {
this.first = first;
this.last = last;
this.fullName = personFullName;
}
var dude = new Person("Michael", "Jackson");
alert(dude.fullName());
哪些警報 「邁克爾·傑克遜」。我改成了叫從構造personFullName
,而不是分配函數對象:
function personFullName() {
return this.first + ' ' + this.last;
}
function Person(first, last) {
this.first = first;
this.last = last;
this.fullName = personFullName();
}
var dude = new Person("Michael", "Jackson");
alert(dude.fullName);
我期望的「全名」屬性現在是一個字符串,而不是一個功能。但現在它提醒「undefined undefined」。任何人都可以解釋爲什麼我的版本不起作用?
查看此答案,瞭解「this」的工作原理的完整說明:http://stackoverflow.com/questions/13441307/how-does-the-this-keyword-in-javascript-act-within-an-object -literal/13441628#13441628 – slebetman