2013-02-13 46 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"