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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With