我一直在嘗試在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的方法,就像我說我想這是一樣的原型方法。
MDN使用第一種方法:https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Global_Objects/Object/create – ppasler
@charty雖然你的ES6類看起來像你的V2,但它內部更像V1。 – vothaison
我想我不需要更新答案。這是一個很好的解釋:https://reinteractive.com/posts/235-es6-classes-and-javascript-prototypes;請檢查一下。 – vothaison