Create a "factory" that creates objects - Node.js Object

Node.js examples for Object:Object Operation

Description

Create a "factory" that creates objects

Demo Code


// Define a function called `Robot()`.
// Typically, we would create a new instance with `new Robot()`.
// Instead, create a "factory" that creates more `Robot`s with this call:
// ---//from w  w  w .  j  av a 2  s.com
// Robot.new()
//
// When `Robot.new()` is called it should return a new instance with the prototype set to Robot e.g.:
// ---

function Robot(){

}

Robot.prototype.alarm = function(){
  console.log('Danger, Danger!');
}

Robot.new = function(){
  var F = function(){};
  F.prototype = new this();
  return new F();
}

var robby = Robot.new();

robby.alarm();

Related Tutorials