Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Two ways of declaring methods in Javascript [duplicate]

Tags:

javascript

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?

like image 563
ajsie Avatar asked Nov 06 '10 19:11

ajsie


1 Answers

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.

like image 193
hvgotcodes Avatar answered Oct 05 '22 19:10

hvgotcodes