【发布时间】:2017-05-12 14:53:36
【问题描述】:
我一直在尝试更深入地学习 Javascript 中的 OOP。在 JavaScript 中创建类和对象有不同的方法。如果我理解正确的话,下面是两种最流行的方式。但是我不明白他们之间有什么不同。这些方法给出了完全相同相同的结果。如果它们是相同的,那为什么会有两种不同的方式呢?
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 的方法,就像我说的,我猜这与原型方法相同。
【问题讨论】:
-
@charty 虽然你的 ES6 类看起来像你的 V2,但在内部它更像 V1。
-
我想我不需要更新答案。这是一个很好的解释:reinteractive.com/posts/…;请检查一下。
标签: javascript class oop object