Node: Prototype Inheritance

Function construction in Node is pretty straight forward:

function someFunction(){

console.log(“hi”);

}

Functions can also be assigned to an object like so:

var greeting = function someFunction(){

console.log(“hi”);

}

You can also follow a class type pattern doing something such as:

function Car(make, model, year){

this.make = make;

this.model = model;

this.year = year;

}

var prius = new Car(‘Toyota’,’Prius’,2006)

Similari in other languages, the above instantiates the model Car with set values, creating it as an object called Prius.

We can flavor the prototype (the inheritance of the object) by adding in the prototype keyword like so:

function Car(make, model, year){

this.make = make;

this.model = model;

this.year = year;

}

Car.prototype.info = function(){

console.log(“This car is a ” + this.model + ” of this ” + this.year);

}

var prius = new Car(‘Toyota’,’Prius’,2006);

prius.info();

In the simple prototype example above, we’ve added a precondition of output to the console, when the object is created.

Node: Prototype Inheritance
User Rating: 0 (0 votes)