6

Possible Duplicate:
Use of 'prototype' vs. 'this' in Javascript?

I've seen both these two ways of declaring methods in Javascript:

var User = function() {
    this.name = 'Foo';
    this.greet = function() {
        console.log('Hello!');
    }
}

and

var User = function() {
    this.name = 'Foo';
}

User.prototype.greet = function() {
    console.log('Hello!');
}

What are the differences?

Community
  • 1
  • 1
ajsie
  • 77,632
  • 106
  • 276
  • 381
  • 1
    Relevant: http://stackoverflow.com/questions/1635116/javascript-class-method-vs-class-prototype-method – DaiYoukai Nov 06 '10 at 20:26

2 Answers2

3

If you are creating a 'class', you want to use the second. I say class in quotes because javascript doesn't have the formal notion of a class, since it uses prototypal inheritance.

Every object you create in JS inherits its properties from the prototype. In the second example, every User you create will get the method 'greet' from the prototype. In your first example, every User will get the method greet from the User constructor.

The second is superior because the first approach effectively creates a new copy of the 'greet' function for every object created. In the second approach, every User object has a pointer to the greet function, so it is in effect reused by the interpreter. Note this is NOT the same as saying 'greet' is static.

hvgotcodes
  • 118,147
  • 33
  • 203
  • 236
1

in the first example you create your User function, then you add the greet function to that instance (giving User.greet()). But since you have this in the constructor function then it will be added to all instances.

In the second example, you define your User constructor. Then you define the greet prototype for all instances of User. This comes out to the same thing as your first example here, but if formed differently, the change becomes more obvious

var User = function() {
    this.name = 'Foo';
}

var a=new User();
var b=new User();
a.greet=function(){
    alert(this.name);
}
/*a has the greet function, b does not*/

User.prototype.greet=function(){
    alert(this.name);
}
/*a and b both have the greet function now, since they are both of class User*/
rtpg
  • 2,419
  • 1
  • 18
  • 31