Prototypes - Inheritance and Constructors


// using inheritance, we can create new Objects with our exisitnjhg objects as prototypes
var shoe = {size: 6, gender: "women", construction: "slipper" };
var magicShoe = Object.create(shoe);
console.log(magicShoe);

// add new properties to our object
magicShoe.jewels = "ruby";
magicShoe.travelAction = "click heels";
magicShoe.actionsRequired = 3;
console.log(magicShoe);

// a quick look at the prototype chain

// is shoe a prototype of Object
Object.prototype.isPrototypeOf(shoe); // retuns true

// is magicShoe a prototype of shoe
shoe.isPrototypeOf(magicShoe); // retuns true

// is shoe a prototype of magicShoe
magicShoe.isPrototypeOf(shoe); // retuns false

// is magicShoe a prototype of Object
// looks all the way up the prototype chain
Object.prototype.isPrototypeOf(magicShoe); // retuns true

// can we use the same prototype to make different types of shoes?
// we need to determine common properties of a shoes class
// a class is a set of objects that all share and inherit the same basic prototype

// A constructor allows us to set up inheritance while also assigning specific property values
// Capitalising the function's name distinguishes it as a maker of an entire class of objects

// assigning a prototype to a constructor

function Shoe( shoeSize, shoeColor, forGender, constructStyle) {
    this.size = shoeSize;
    this.color = shoeColor;
    this.gender = forGender;
    this.construction = constructStyle;
}

Shoe.prototype = {
    putOn : function(){ alert("Yout " + this.construction + "'s" +" on, dude!"); },
    takeOff : function(){ alert("Phew! Somebody's size " + this.size + "'s" + " are fragrant!"); }
};

// by putting the functions in the prototype we make the constructor more efficient
// every instance will inherit the prototype


var beachShoe = new Shoe(10, "blue", "women", "flipflop");
console.log(beachShoe);
console.log(beachShoe.gender);
beachShoe.putOn();
beachShoe.takeOff();

// add straps to the shoes
beachShoe.straps = 2;

beachShoe.hasOwnProperty("construction"); // retuns true as shoes constructor passes inheritance
By Chris Armstrong
Saturday 8th March 2014

Comments

There are currently no comments

Make a comment