我一直在努力更深入地学习JavaScript中的面向对象编程。在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的方法,就像我说的一样,我猜这与原型方法相同。