2012-05-17 41 views
1

Possible Duplicate:
Advantages of using prototype, vs defining methods straight in the constructor?自定義類 - 這與原型?

什麼是在JavaScript中創建自定義類和公共方法的最佳實踐,更重要的是...爲什麼?

使用'this'創建公共方法?

var myClass = function() { 

    this.myVar = "this is my value"; 

    this.myFunc = function() { 
     alert(this.myVar); 
    }; 

    this.myFunc(); 
}; 

- 或 - 使用 '原型' 創建公共的方法呢?

var myClass = function() { 

    this.myFunc(); 
}; 

myClass.prototype = { 

    myVar: "this is my value", 

    myFunc: function() { 
     alert(this.myVar); 
    } 

}; 

非常感謝!!!

+0

這個問題是問天至少一次... –

回答

0

聲明一個使用原型的方法將意味着該方法在任何時候都可用於該原型的一個實例,只要該實例是在該方法聲明之後創建的。

使用this.foo = function(){ ... }在構造函數中聲明它意味着該方法僅在構造函數中聲明它的位置後可用。

作爲一個簡單的例子,我們來看看命名和匿名函數。

在下面,我們聲明一個命名的函數並調用它兩次。請注意,該函數執行第一次調用罰款,即使在第一次調用是函數的聲明之前:

foo(); 

function foo() 
{ 
    alert("foo"); 
} 

foo(); 

現在,而不是一個命名的功能,我們將使用存儲在一個變量的匿名函數:公告現在第一個電話會導致錯誤,因爲此時foo未定義。

foo(); 

var foo = function() 
{ 
    alert("foo"); 
} 

foo(); 

原型的(概念)相似的方式工作,當我們改變一個函數的原型,我們影響了它會創建一個函數的實例之前。所以下面的工作正常:

function f() 
{ 
    this.bar(); 
} 

f.prototype.bar = function() 
{ 
    alert("bar"); 
}; 

var f1 = new f(); 

注意f.prototype.bar,我們叫它行後物理聲明。現在將其與this. ...方法進行比較。如預期

function g() 
{ 
    this.h = function(){ 
     alert("h"); 
    }; 

    this.h(); 
} 

var g1 = new g(); 

雖然這並不因爲我們試圖調用this.h我們賦值之前,它下面的工作:

function g() 
{ 
    this.h(); 

    this.h = function(){ 
     alert("h"); 
    }; 
} 

var g2 = new g(); 

注意,雖然,影響的函數的原型仍然使用將匿名函數分配給原型屬性的機制。這意味着即使使用原型方法,如果在向原型添加函數之前實例化原型實例,我們也可能會出錯。例如,以下工作正常:

function f() 
{ 
    this.bar(); 
} 

f.prototype.bar = function() 
{ 
    alert("bar"); 
}; 

var f1 = new f(); 

,但如果我們移動var f1 = new f();分配上面f.prototype.bar我們得到了一個錯誤:

function f() 
{ 
    this.bar(); 
} 

var f1 = new f(); 

f.prototype.bar = function() 
{ 
    alert("bar"); 
}; 
+0

非常感謝您的詳細解答! – SpaceCowboy2071