Using the Prototype's Methods and Properties

All the methods and properties added to the prototype are directly available as soon as a new object created using the constructor.

We can access all the methods and properties already defined from newtoy object created using the Gadget() constructor.

var newtoy = new Gadget('webcam', 'black');

newtoy.name;
"webcam"

newtoy.color;
"black"

newtoy.whatAreYou();
"I am a black webcam"

newtoy.price;
100

newtoy.rating;
3

newtoy.getInfo();
"Rating: 3, price: 100"
Note
Objects are passed by reference in JavaScript, and therefore the prototype is not copied with every new object instance. You can modify the prototype at any time and all objects (even those created before the modification) will inherit the changes.

Let's continue the example, adding a new method to the prototype:

Gadget.prototype.get = function(what) {
    return this[what];
};

Even though newtoy was created before the get() method was defined, newtoy will still have access to the new method:

snippet
newtoy.get('price');
100

newtoy.get('color');
"black"
Related Tutorial
Follow Us
https://www.facebook.com/Rookie-Nerd-638990322793530 https://twitter.com/RookieNerdTutor https://plus.google.com/b/117136517396468545840 #
Contents