2013-02-13 47 views
0

我想从https://developer.mozilla.org/en-US/docs/JavaScript/A_re-introduction_to_JavaScript了解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中的对象,但我无法理解这个概念?

回答

1

因为Person对象正在为自己分配一个方法,而不是函数的结果。这就是它不称为功能的原因。

这样你就可以做到这一点。

var p = new Person("Matt", "M"); 
p.fullName(); // Returns "Matt M" 
p.fullNameReversed(); // Returns "M, Matt"