1

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 ?

copenndthagen
  • 49,230
  • 102
  • 290
  • 442

1 Answers1

1

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/

Beri
  • 11,470
  • 4
  • 35
  • 57
  • Is the first version `this.sayHi` what Douglas Crockford calls privileged method? – Stack0verflow Jan 29 '15 at 14:20
  • 1
    @Stack0verflow: Yes it is, because it would be privileged to access the constructor's local `name` *variable* directly (not only the "public" `.name` property) – Bergi Jan 29 '15 at 14:21