2016-12-28 70 views
3

我一直在嘗試在JavaScript中更深入地學習OOP。在JavaScript中創建類和對象的方法有很多。如果我理解正確,那麼下面兩種最流行的方法。但是我不明白他們之間有什麼不同。該方法正好給出正好相同的結果。如果它們是相同的,那麼爲什麼有兩種不同的方式?JavaScript Object創建方法有什麼區別?

V1

function Country(name){ 
    this.name=name; 
    this.cities=[]; 
    this.continent; 
} 

Country.prototype={ 
    constructor:Country, 
    addCity:function(name){ 
     this.cities.push(name) 
    }, 
    setContinent:function(continent){ 
     this.continent=continent; 
    } 
} 

V2

function Country(name){ 
    this.name=name; 
    this.cities=[]; 
    this.continent; 

    this.addCity=function(name){ 
     this.cities.push(name); 
    } 

    this.setContinent=function(continent){ 
     this.continent=continent; 
    } 
} 

感謝您的四大答案。我正確地理解了這種差異。也許你知道,從EcmaScript6開始,就可以創建類似於Java的類和對象。

加成

然後這個系統是相同的原型的方法和沒有缺陷的使用。

class Country 
{ 

    constructor(name){ 
     this.name=name; 
     this.cities=[]; 
     this.continent; 
    } 

    addCity(name){ 
     this.cities.push(name); 
    } 

    setContinent(continent){ 
     this.continent=continent; 
    } 
} 

c1 = new Country() 
c2 = new Country() 
console.log(c1.addCity == c2.addCity) // gives true 

我已經試過@ vothaison的方法,就像我說我想這是一樣的原型方法。

+0

MDN使用第一種方法:https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Global_Objects/Object/create – ppasler

+0

@charty雖然你的ES6類看起來像你的V2,但它內部更像V1。 – vothaison

+1

我想我不需要更新答案。這是一個很好的解釋:https://reinteractive.com/posts/235-es6-classes-and-javascript-prototypes;請檢查一下。 – vothaison

回答

5

你的兩種方式是不一樣的,V1是要走的路。

使用V1,創建的所有新實例將使用addCity方法和setContinent方法的相同innstace。

鑑於在V2中,所有實例都有自己的addCity方法和setContinent方法的實例,這是浪費資源。

您使用此代碼測試他們:

c1 = new Country() 
c2 = new Country() 
c1.addCity == c2.addCity // true in V1, false in V2 
+0

我更新了我的問題。你可以看一下嗎? – amone

1

V1是要走的推薦方式。

它使用Prototype Pattern

的原型模式創建新的對象,但而不是創建非初始化的對象它返回被初始化與它從一個原型複製值的對象 - 或樣品 - 對象。 Prototype模式也被稱爲屬性模式。

MDN解釋利弊非常好:Inheritance and the prototype chain

相關問題