example

function Text() { } var text = new Text(); Text. name = 'test '; console.log(text.name, 'text')Copy the code

In this case Text is a constructor, and we use new to create an instance object Text.

prototype

Function Text() {} text.prototype.name = 'test '; var text1 = new Text(); var text2 = new Text(); console.log(text1.name, text1.name, 'text')Copy the code

The function’s prototype property points to an object that is the prototype of the instance created by calling the constructor, namely text1 and text2 in this case.

What is a prototype

Every JavaScript object (except null) is associated with another object when it is created, and this object is called a prototype, from which each object “inherits” properties.

proto

This is a property that every JavaScript object (except null) has, called __proto__, which points to the object’s prototype.

Function Text() {} text.prototype.name = 'test '; var text1 = new Text(); var text2 = new Text(); // console.log(text1.name, text1.name, 'text') console.log(text1.__proto__ === Text.prototype); // trueCopy the code

constructor

Each stereotype has a constructor property pointing to the associated constructor.

Function Text() {} text.prototype.name = 'test '; var text1 = new Text(); var text2 = new Text(); // console.log(text1.name, text1.name, 'text') // console.log(text1.__proto__ === Text.prototype); console.log(Text === Text.prototype.constructor, Text === text1.__proto__.constructor, ES5 console.log(object.getProtoTypeof (text1) === text.prototype) // trueCopy the code

Examples and prototypes

When an instance property is read, if it cannot be found, it looks for the property in the stereotype associated with the object. If not, it looks for the stereotype until it reaches the topmost level.

Function Text() {} text.prototype.name = 'test '; var text1 = new Text(); // var text2 = new Text(); // console.log(text1.name, text1.name, 'text') // console.log(text1.__proto__ === Text.prototype); // console.log(Text === Text.prototype.constructor, Text === text1.__proto__.constructor, // true true text1.name = '123'; console.log(text1.name) // 123 delete text1.name; The console. The log (text1. Name) / / testCopy the code

Prototype of prototype

var obj = new Object(); Obj.name = 'test' console.log(obj.name) // TestCopy the code

The prototype Object is generated through the Object constructor

Prototype chain

console.log(Object.prototype.__proto__ === null) // true
Copy the code

Object. Prototype can be stopped when the prototype is looking for properties. A chain of interconnected prototypes is called a prototype chain