对方法原理的理解有疑惑
我了解函数并且我知道
function hello() {
alert('Hello World');
}
与
相同var hello = function() {
alert('Hello World');
}
现在,我的问题是什么。
这是我使用一种方法的对象。我不明白为什么
function people()
中的 yarsLeft
不需要括号
我正在寻找合乎逻辑的解释。
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();
最佳答案
当您使用不带括号的函数名称 (()
) 时,您正在设置对函数本身 的引用。
当您使用带括号的相同函数时,您正在执行该函数。
因此这条线
this.yearsUntilRetire = yearsLeft;
正在设置 yearsUntilRetire
以指向函数。此后你可以这样做:
this.yearsUntilRetire(); // execute the yearsLeft function.
Why I can't write this.yearsUntilRetire() = yearsLeft or this.yearsUntilRetire = yearsLeft();
在第一种情况下,您不能将调用函数的结果设置为不同的结果 - 这是一个语法错误。
在第二种情况下,您可以 - 它将变量 yearsUntilRetire
设置为调用函数 yearsLeft
关于JavaScript - 理解方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34717462/