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.
Objects created using object literal are singletons, this means when a change is made to the object, it affects the object entire the script. Whereas if an object is created using constructor function and a change is made to it, that change won't affect the object throughout the script.
Objects created using object literals are singletons. This means when a change is made to the object, it affects that object across the entire script. Object defined with a function constructor let us have multiple instances of that object. This means change made to one instance, will not affect other instances.
The prototype property is set to function when it is declared. All the functions have a prototype property. proto property that is set to an object when it is created using a new keyword. All objects behavior newly created have proto properties.
Now the question is when should we be using Literal notation and constructor notation. The point is when we need only one instance with the same values then we can go with the literal notation else if we may need multiple instances, like the instance of a class, we can go for the constructor notation.
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.
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