Javascript - Combination Constructor/Prototype Pattern


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.


function Person(name, age, job){ = name;//from ww w .j  a  va 2 s.c om
    this.age = age;
    this.job = job;
    this.friends = ["A", "B"];

Person.prototype = {
    constructor: Person,
    sayName : function () {

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


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