Javascript - Class Prototype Pattern

Introduction

Each function has a prototype property.

The prototype property contains properties and methods that are available to instances of a particular reference type.

For example:

Demo

function Person(){
}

Person.prototype.name = "First";
Person.prototype.age = 29;//from  w  w  w  .j av  a2  s  .c o m
Person.prototype.job = "writer";
Person.prototype.sayName = function(){
    console.log(this.name);
};

var person1 = new Person();
person1.sayName();   //"First"

var person2 = new Person();
person2.sayName();   //"First"
console.log(person1.sayName == person2.sayName);  //true

Result

Here, the properties and the sayName() method are added directly to the prototype property of Person, leaving the constructor empty.

Unlike the constructor pattern, the properties and methods are all shared among instances.

person1 and person2 are both accessing the same set of properties and the same sayName() function.

The isPrototypeOf() method can determine if the relationship exists between objects.

console.log(Person.prototype.isPrototypeOf(person1));  //true
console.log(Person.prototype.isPrototypeOf(person2));  //true

In this code, the prototype's isPrototypeOf() method is called on both person1 and person2.

Since both instances have a link to Person.prototype, it returns true.

Object.getPrototypeOf(), which returns the value of [[Prototype]] in all supporting implementations. For example:

console.log(Object.getPrototypeOf(person1) == Person.prototype);  //true
console.log(Object.getPrototypeOf(person1).name);  //"First"

Related Topics