Reputation: 3082
i came across this post http://www.webmasterworld.com/javascript/3066162.htm about how in javascript when you instantiate an object literal if it has methods defined in it then each time one is instantiated its methods are copied as well. so if you have a bunch of instances of the object literal then the copied methods would begin to add up in memory.
how ever he/she states that using prototype to make your methods is more efficient because the methods are not copied for each instance of the constructor object.
is this true? because i was under the impression that prototype allowed you to add properties/methods even after the object was instantiated rather than within the object when its first created.
Upvotes: 9
Views: 4199
Reputation: 12443
Defining methods on a constructor function's prototype is similar to a class definition in other languages. The methods defined in a Java class, for example, are shared by all instances of that class. The methods defined on a constructor function's prototype, in Javascript, are shared by all instances created from that constructor function.
The main difference in the example above is variable declarations. A variable that is defined on a prototype will be shared among instances where as every instance of a class will have its own copy of the variables in the class definition.
The easiest way to understand would be through some experimentation. http://jsfiddle.net/3vn4A/
In Firefox object's can access their prototype directly via the __proto__
pointer. Object.getPrototypeOf(obj)
is the standard way for an object to programmatically refer to its prototype.
Upvotes: 1
Reputation: 35409
It is true, that is why there is a prototype
.
// define Function foo
function Foo()
{
this.x = 1;
this.bar = 'bar';
}
// define method on Foo's prototype
Foo.prototype.helloBar = function()
{
alert(this.bar);
}
var foobar = new Foo();
foobar.helloBar(); // alerts "bar"
Using Foo.prototype
prevents the unnecessary extra bits associated with redefining hellobar
for every instance new Foo()
.
Upvotes: 10
Reputation: 7110
When you create an object like this:
function Car(c) {
this.color = c;
this.drive = function() {};
}
You're actually creating a copy of the drive function for each Car that you create. In Javascript, every object has a prototype pointer and properties/methods from that prototype propagate down the tree to child objects.
When you do:
function Car(c) {this.color=c};
Car.prototype.drive = function {};
and then create a few car objects you end up with this instead:
{drive: function(){}} / | \ car1 (red) car2 (blue) car3 (green)
The drive
function is shared between all the Car objects. It's a shame the syntax for doing this in Javascript is so awkward.
Upvotes: 15