raf*_*fr3 4 javascript oop methods
我对理解方法原理有疑问.
我理解功能,我知道
function hello() {
alert('Hello World');
}
Run Code Online (Sandbox Code Playgroud)
是相同的
var hello = function() {
alert('Hello World');
}
Run Code Online (Sandbox Code Playgroud)
现在,我的问题是什么.
这是我的一个方法的对象.我不明白为什么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;
}
Run Code Online (Sandbox Code Playgroud)
创建对象
var test = new people('Superman', 50);
test.yearsUntilRetire(); // I understand this code and calling a method in that way
Run Code Online (Sandbox Code Playgroud)
为什么我不能写this.yearsUntilRetire() = yearsLeft
或this.yearsUntilRetire = yearsLeft();
当您使用没有括号(()
)的函数名称时,您将设置对函数本身的引用.
当您使用与括号相同的功能时,您正在执行该功能.
所以这一行
this.yearsUntilRetire = yearsLeft;
Run Code Online (Sandbox Code Playgroud)
设置yearsUntilRetire
为指向该功能.此后你可以这样做:
this.yearsUntilRetire(); // execute the yearsLeft function.
Run Code Online (Sandbox Code Playgroud)
为什么我不能写这个.yearsUntilRetire()= yearsLeft或this.yearsUntilRetire = yearsLeft();
在第一种情况下,您不能将调用函数的结果设置为不同的结果 - 这是语法错误.
在第二种情况下,您可以 - 它将变量设置yearsUntilRetire
为调用函数的结果yearsLeft
归档时间: |
|
查看次数: |
60 次 |
最近记录: |