I've been trying to learn OOP in Javascript more deeply.There're different ways of creating class and objects in JavaScript. If I understood correctly, two most popular ways are the ones below. But the thing I don't understand what is the different between them. The methods are giving exactly the same result. If they are identical then why there are two different ways?
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;
}
}
Thank your four great answers. I understood the difference correctly. Probably you know, it's been possible to create class and objects like in Java as of EcmaScript6.
Addition
Then this system is identical to prototype method and there is no drawback to use.
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
I've tried @vothaison's method and like I said I guess this is the same as the prototype method.
Your two ways are not the same, and V1 is the way to go.
With V1, all new instances of Country created will use the same innstace of addCity method and setContinent method.
Whereas in V2, all instances have their own instance of addCity method and setContinent method, which is a waste of resource.
You test them with this code:
c1 = new Country()
c2 = new Country()
c1.addCity == c2.addCity // true in V1, false in V2
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With