What's the difference?
var A = function () {
this.x = function () {
//do something
};
};
or
var A = function () { };
A.prototype.x = function () {
//do something
};
What's the difference?
var A = function () {
this.x = function () {
//do something
};
};
or
var A = function () { };
A.prototype.x = function () {
//do something
};
The first example changes the interface for that object only. The second example changes the interface for all object of that class.
In most cases they are essentially the same, but the second version saves memory because there is only one instance of the function instead of a separate function for each object.
A reason to use the first form is to access "private members". For example:
var A = function () {
var private_var = ...;
this.x = function () {
return private_var;
};
this.setX = function (new_x) {
private_var = new_x;
};
};
Because of javascript's scoping rules, private_var is available to the function assigned to this.x, but not outside the object.
I believe that @Matthew Crumley is right. They are functionally, if not structurally, equivalent. If you use Firebug to look at the objects that are created using new
, you can see that they are the same. However, my preference would be the following. I'm guessing that it just seems more like what I'm used to in C#/Java. That is, define the class, define the fields, constructor, and methods.
var A = function() {};
A.prototype = {
_instance_var: 0,
initialize: function(v) { _instance_var = v; },
x: function() { alert(_instance_var); }
};
EDIT Didn't mean to imply that the scope of the variable was private, I was just trying to illustrate how I define my classes in javascript. Variable name has been changed to reflect this.
As others have said the first version, using "this" results in every instance of the class A having its own independent copy of function method "x". Whereas using "prototype" will mean that each instance of class A will use the same copy of method "x".
Here is some code to show this subtle difference:
// x is a method assigned to the object using "this"
var A = function () {
this.x = function () {
alert('A');
};
};
A.prototype.updateX = function(value) {
this.x = function() {
alert(value);
}
};
var a1 = new A();
var a2 = new A();
a1.x(); // Displays 'A'
a2.x(); // Also displays 'A'
a1.updateX('Z');
a1.x(); // Displays 'Z'
a2.x(); // Still displays 'A'
// Here x is a method assigned to the object using "prototype"
var B = function () { };
B.prototype.x = function () {
alert('B');
};
B.prototype.updateX = function(value) {
B.prototype.x = function() {
alert(value);
}
}
var b1 = new B();
var b2 = new B();
b1.x(); // Displays 'B'
b2.x(); // Also displays 'B'
b1.updateX('Y');
b1.x(); // Displays 'Y'
b2.x(); // Also displays 'Y' because by using prototype we
// have changed it for all instances
As others have mentioned, there are various reasons to choose one method or the other. My sample is just meant to clearly demonstrate the difference.