Javascript - How to create a library from a prototype

About

This page shows you how to create a library from a prototype

Example

  • The library
var Point = function(loc) {
   // The prototype creation is important to be recognized as an ''instanceof''
   var obj = Object.create(Point.prototype);
   obj.loc = loc;
   return obj;
}

// Prototype added after the var declaration otherwise it does not exist
Point.prototype.move = function(){
    this.loc++;
}
  • The main
var point1 = Point(1);
point1.move();
var point2 = Point(2);
point2.move();


console.log(Point.prototype.constructor);
console.log(point1.constructor);

console.log(point1 instanceof Point);

Powered by ComboStrap