Saturday, May 16, 2015

JavaScript Prototype Chain

A prototype is a template to construct an object.  All objects in Javascript is has a base prototype which is the JavaScropt Object.  Object inherit the methods (e.g. ToString) and properties of the prototype object.

Each object has an internal property called _proto_ which point to the prototype object, which in turn points to the Object which is the protoype for all other objects in Javascript

For example, the following defines a constructor for object car and a method

function car(vendor, model, year) {
    this.vendor = vendor;
    this.model = model;
    this.make = year;
}

car.prototype.checkcurmodel = function() {
    if this.make = "2015" {alert("current year");
}

The following defines 2 cars

var car1 = new car("toyota", " corolla", "1995");
var car2 = new car("vw", "passat", "2014"_;

car1 and car2's _proto_ field points to car.prototype object.  The constructor car also contains a _proto_ pointing to the car.prototype object.  The car.prototype object contains a constructor field pointing to the car constructor.  It also has a _proto_ field point to the Object prototype which contains base methods such as toString etc.

Accessing field and calling method require a search of the prototype chain.

No comments: