我正在尝试从https://developer.mozilla.org/en-US/docs/JavaScript/A_re-introduction_to_JavaScript了解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;
}
我很困惑为什么函数personFullName()被调用为
this.fullName = personFullName;
为什么它不被称为;
this.fullName = personFullName();
以下相同;
this.fullNameReversed = personFullNameReversed;
我知道函数是javascript中的对象,但我无法理解这个概念?
答案 0 :(得分:1)
因为Person
对象为自己指定了方法,而不是函数的结果。这就是没有调用函数的原因。
这样你就可以做到这一点。
var p = new Person("Matt", "M");
p.fullName(); // Returns "Matt M"
p.fullNameReversed(); // Returns "M, Matt"