Adding Methods and Properties Using the Prototype

For the new object(created by using constructor function) you can augment (adding methods and properties to) using this object..

Below is a constructor function Gadget() which uses this to add two properties and one method to the objects.

snippet
function Gadget(name, color) {
    this.name = name;
    this.color = color;
    this.whatAreYou = function() {
        return 'I am a ' + this.color + ' ' + this.name;
    }
}

Another way to add functionality to the objects this constructor, is by adding methods and properties to the prototype property of the constructor function.

Since prototype contains an object, you can add more properties like below.

snippet
Gadget.prototype.price = 100;
Gadget.prototype.rating = 3;
Gadget.prototype.getInfo = function() {
    return 'Rating: ' + this.rating + ', price: ' + this.price;
};

Instead of adding to the prototype object, you can overwrite the prototype completely to achieve the above result, replacing it with an object of your choice:

snippet
Gadget.prototype = {
    price: 100,
    rating: 3,
    getInfo: function() {
        return 'Rating: ' + this.rating + ', price: ' + this.price;
    }
};
Related Tutorial
Follow Us
https://www.facebook.com/Rookie-Nerd-638990322793530 https://twitter.com/RookieNerdTutor https://plus.google.com/b/117136517396468545840 #
Contents +