mardi 17 février 2015

What is the correct way to add methods to a javascript class?

I'm fairly new to the concept of javascript classes. When I first learned, I was taught to use a pattern similar to the way you would create classes in PHP:



function MyClass(userv) {
this.userv = userv;

this.emotion = function(emo) {
alert('I ' + emo + this.userv);
}

this.sayHello = function() {
alert('Hello ' + this.userv);
}

}

var mc = new MyClass('Mary');
mc.emotion('love');
mc.sayHello();


But since then I've seen this pattern for creating js classes:



function MyClass(userv) {
this.userv = userv;
}

MyClass.prototype.emotion = function(emo) {
alert('I ' + emo + this.userv);
}

MyClass.prototype.sayHello = function() {
alert('Hello ' + this.userv);
}

var mc = new MyClass('Mary');
mc.emotion('love');
mc.sayHello();


Both seem to work just fine. Is there a reason to not use the first pattern? It seems easier to comprehend. But perhaps there are optimization or other reasons I can't see for using the second pattern.


Aucun commentaire:

Enregistrer un commentaire