In Object-oriented Javascript, we can define a method inside an object as
this.myMethod = function() {
}
OR
we can use the prototype way
MyClass.prototype.myMethod = function() {
}
What are the differences between the 2 techniques ?
In Object-oriented Javascript, we can define a method inside an object as
this.myMethod = function() {
}
OR
we can use the prototype way
MyClass.prototype.myMethod = function() {
}
What are the differences between the 2 techniques ?
 
    
    First:
function Person(name){
    this.name = name
    this.sayHi = function(){
        return 'Hi, I am ' + this.name
    }
}
Second:
function Person(name){
    this.name = name
}
Person.prototype.sayHi = function(){
    return 'Hi, I am ' + this.name
}
In the first version, each time you create a person, a new sayHi function will be created for him, where as in the second version, only one sayHi function is ever created, and is shared amongst all persons that are created - because Person.prototype is their parent. Thus, declaring methods on the prototype is more memory efficient.
Source: http://tobyho.com/2010/11/22/javascript-constructors-and/
