[英]What is the difference between two ways of defining object methods in Javascript?
[英]What is the difference between JavaScript Object creation methods?
我一直在尝试更深入地学习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的方法,就像我说的那样,我猜这与原型方法相同。
你的两种方式是不一样的,V1是要走的路。
使用V1,创建的Country的所有新实例将使用相同的addCity方法和setContinent方法。
而在V2中,所有实例都有自己的addCity方法实例和setContinent方法,这是浪费资源。
您使用以下代码测试它们:
c1 = new Country()
c2 = new Country()
c1.addCity == c2.addCity // true in V1, false in V2
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.