我對理解方法的原理有所懷疑。
我理解的功能,我知道JavaScript - 瞭解方法
function hello() {
alert('Hello World');
}
相同
var hello = function() {
alert('Hello World');
}
現在,什麼是我的問題。
這是我的一個方法的對象。我不明白爲什麼 括號不需要在yarsLeft
裏面function people()
我在尋找合乎邏輯的解釋。
function people(name, age) {
this.name = name;
this.age = age;
this.yearsUntilRetire = yearsLeft; // this is confised for me
}
function yearsLeft() {
var numYears = 65 - this.age;
return numYears;
}
創建對象
var test = new people('Superman', 50);
test.yearsUntilRetire(); // I understand this code and calling a method in that way
爲什麼我不能寫this.yearsUntilRetire() = yearsLeft
或this.yearsUntilRetire = yearsLeft();
這是一個函數引用。函數可以像JS中的任何其他類型一樣引用和傳遞。 – Teemu
'()'將調用(調用)該函數。您正在將函數表達式設置爲'this.yearsUntilRetire'。一旦你調用'this.yearsUntilRetire()',函數表達式就會被執行。 – Rayon