Snippet 1 (Adding methods to a class)
var myClass = function(prop1, prop2) {
this.prop1 = prop1;
this.prop2 = prop2;
this.method1 = function() {//blah}
this.method2 = function() {//blahblah}
}
Snippet 2 (Adding methods to a class's prototype)
this.prop1 = prop1;
this.prop2 = prop2;
}
myClass.prototype.method1 = function() {//blah}
myClass.prototype.method2 = function() {//blahblah}
Snippet 1
- Two functions are created for every construction of
myClass
can give you access to private variables and constructor arguments
Snippet 2
- the two functions are created once: when the prototype is filled.
- gives better memory usage
- Methods that inherit via the prototype chain can be changed universally for all instances
- For instance, you can extend the built-in String object by adding a trim function to it and all future instance of that object will share the trim function.
http://stackoverflow.com/questions/4508313/advantages-of-using-prototype-vs-defining-methods-straight-in-the-constructor
No comments:
Post a Comment