Combination Constructor and Prototype Pattern

Description

The constructor pattern defines instance properties, whereas the prototype pattern defines methods and shared properties.

Each instance ends up with its own copy of the instance properties, but they all share references to methods.

Example


function Person(name, age, job){/*from  ww  w  . j  a  va2  s .  c o  m*/
   this.name = name;
   this.age = age;
   this.job = job;
   this.friends = ["A", "B"];
}

Person.prototype = {
   constructor: Person,
   sayName : function () {
      console.log(this.name);
   }
};

var person1 = new Person("XML", 29, "Mark up");
var person2 = new Person("CSS", 27, "Style");

person1.friends.push("C");

console.log(person1.friends);    
console.log(person2.friends);    
console.log(person1.friends === person2.friends);  //false
console.log(person1.sayName === person2.sayName);  //true

The code above generates the following result.

Note

This is the default pattern to use for defining reference types.





















Home »
  Javascript »
    Javascript Introduction »




Script Element
Syntax
Data Type
Operator
Statement
Array
Primitive Wrapper Types
Function
Object-Oriented
Date
DOM
JSON
Regular Expressions