Constructor Function - Node.js Object

Node.js examples for Object:Constructor

Description

Constructor Function

Demo Code

// //from   w w  w  .  ja va  2s  .co m
console.log("");
console.log("*** Constructor Function ***");

function Person(firstName, lastName) {
  this.firstName = firstName;
  this.lastName = lastName;
//  this.kind = "Person";
//  this.name = function() { return this.firstName + " " + this.lastName; };
}

// New: Moved down from Constructor Function for better code reuse by adding properties to prototype object
// Note: prototype only applies with new keyword
Person.prototype.kind = "Person"; 

// Note: Function properties behave like static members                                                    
Person.kindStatic = "Person Static";                                                    
Person.prototype.name = function() { return this.firstName + " " + this.lastName; };

// New: Or shortcut
Person.prototype = {
  kind: "Person",
  name: function() { return this.firstName + " " + this.lastName; }
}

// Create objects using Constructor function
var fred2 = new Person("Fred", "Flintstone");
var barney2 = new Person("Barney", "Rubble");

console.log(fred2);
console.log(fred2.name());
console.log(barney2);
console.log(barney2.name());

// New: Check out prototype / static members
console.log(fred2.kind);                                                // Person
console.log(Person.kindStatic);                                         // Person Static
console.log(Person);                                                    // function Person(firstName, lastName) {...}

// prototype of all objects that have a Person prototype
console.log(Person.prototype);                                          // Object {kind: "Person", name: function, constructor: function}

// prototype of fred2 and barney objects, which could be different if it's prototype has been changed                              
console.log(Object.getPrototypeOf(fred2));                              // Object {kind: "Person", name: function, constructor: function}
console.log(fred2.__proto__);                                           // Object {kind: "Person", name: function, constructor: function}
console.log(Object.getPrototypeOf(barney2));                            // Object {kind: "Person", name: function, constructor: function}
console.log(barney2.__proto__);                                         // Object {kind: "Person", name: function, constructor: function}

Related Tutorials