Javascript - Combination Constructor/Prototype Pattern

Introduction

You can create custom types by combining the constructor and prototype patterns.

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

With this approach, each instance ends up with its own copy of the instance properties, but they all share references to methods.

Demo

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

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

var person1 = new Person("First", 29, "Writer");
var person2 = new Person("Tom", 27, "Doctor");

person1.friends.push("new Value");

console.log(person1.friends);    //"Shelby,Court,Van"
console.log(person2.friends);    //"Shelby,Court"
console.log(person1.friends === person2.friends);  //false
console.log(person1.sayName === person2.sayName);  //true

Result

Here, the instance properties are defined in the constructor, and the shared property constructor and the method sayName() are defined on the prototype.