我在MDN(Mozilla開發者網絡)的JavaScript教程中遇到了這段代碼(順便說一句,這是一篇精彩的文章)。 MDN JavaScript Re-introduction在JavaScript中調用函數的屬性?
function personFullName() {
return this.first + ' ' + this.last;
}
function personFullNameReversed() {
return this.last + ', ' + this.first;
}
function Person(first, last) {
this.first = first;
this.last = last;
this.fullName = personFullName;
this.fullNameReversed = personFullNameReversed;
}
什麼讓我感興趣的是函數的調用方式。典型的();不用於在Person函數中進行函數調用。在該人的功能,我們可以看到:
this.fullName = personFullName;
使用的
this.fullName = personFullName();
在此相反,「personFullName」用於像變量或屬性,而不是,它確實是,一功能。有人可以闡明這是爲什麼嗎?
因爲函數沒有在那裏調用。把'alert('foo')'放在任何函數中,看看它沒有出現 – zerkms
它被用作變量,因爲它*是一個變量。它是一個引用函數對象的變量。函數是可以像任何其他對象一樣分配給變量和屬性的對象。 –