我对理解方法的原理有所怀疑。
我理解的功能,我知道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