Javascript - Alternate Prototype Syntax

Introduction

You can overwrite the prototype with an object literal that contains all of the properties and methods:

function Person(){
}
Person.prototype = {
   name : "First",
   age : 29,
   job : "writer",
   sayName : function () {
       console.log(this.name);
   }
};

Here, the Person.prototype property is set equal to a new object created with an object literal.

In this way the constructor property no longer points to Person.

var friend = new Person();
console.log(friend instanceof Object);      //true
console.log(friend instanceof Person);      //true
console.log(friend.constructor == Person);  //false
console.log(friend.constructor == Object);  //true

You can set constructor specifically back to the appropriate value, as shown here:

function Person(){
}

Person.prototype = {
    constructor: Person,
    name : "First",
    age : 29,
    job : "writer",
    sayName : function () {
        console.log(this.name);
    }
};

Restoring the constructor in this manner creates a property with [[Enumerable]] set to true.

Native constructor properties are not enumerable by default.

You can fix it as follows:

function Person(){
}

Person.prototype = {
    name : "First",
    age : 29,
    job : "writer",
    sayName : function () {
        console.log(this.name);
    }
};
Object.defineProperty(Person.prototype, "constructor", {
    enumerable: false,
    value: Person
});

Related Topic