Javascript Prototype & inheritance - Node.js Object

Node.js examples for Object:Prototype

Introduction

All Javascript Objects have a link to a prototype object methods & properties are inherited from this prototype weather it's a custom prototype of the object, or the Object.prototype which every JS object inherits from

you can create a custom prototype with an object constructor function

Demo Code


function Band(singer,guitarist,bassist,drummer) {
  this.singer = singer;// w ww . j  a v  a 2 s . c  o m
  this.guitarist = guitarist;
  this.bassist = bassist;
  this.drummer = drummer;  
}

// then when you use the new keyword to create objects like
var band1 = new Band("A", "B", "C", "D");
var band2 = new Band("X", "Y", "Z", "W");
// they will use the same prototype

// you can't add a property to a prototype in the exact same way as you would with a regular object
// but you can add it directly in the constructor function, or use the prototype property
Band.prototype.nationality = null;
// define property on prototype
band2.nationality = "American";
band1.nationality = "British";
// set individual objects values for property defined on prototype
console.log(band2.nationality);
// Amercian
console.log(band1.nationality);
// British

// you can also add methods to a prototype, in the constructor function or with the prototype property
Band.prototype.fullBand = function () {
  return this.singer + " " + this.guitarist + " " + this.bassist + " " + this.drummer;
  // will return full band when called
}

console.log(band2.fullBand()); 
// X, Y, Z, W
console.log(band1.fullBand());
// A, B, C, D

Note

It's generally, to never try to define methods or properties on the built-in prototypes in javascript.

The prototype chain is traversed when you try access properties of an object.

It will look for the property on the object, on it's prototype & the prototypes prototype if necessary carrying on up the chain until it finds the property it's looking for or reaches the end of the prototype chain

Demo Code

var obj = {prop: "some value"}; 
// obj > Object.prototype > null (end of the chain)

Related Tutorials