In-depth understanding of the JavaScript prototype prototype and prototype chain

What is a prototype?

Once there is a function to create a prototype property that points to an object that is the prototype object, the prototype object.
Summary: The prototype is an object that prototype object.
Here Insert Picture Description
Prototype role is: sharing method
constructor when the object is instantiated, each instance of an object will create an open space for the properties and methods constructor, as follows:

var Person = function(name,age){
	this.name = name;
	this.age = age;
	this.eat = function(){
		console.log("吃饭")
	}
}
var p1 = new Person()
var p2 = new Person()

p1 and p2 have the eat () method, which is created twice, and the same logic functions, only different addresses, thus causing the code redundancy, take up memory, affect performance
in order to solve the above problem, the method of writing in public prototype object, all objects instantiated function can directly access method prototype object

var Person = function(name,age){
	this.name = name;
	this.age = age;
}
Person.prototype.eat = function(){
	console.log("吃饭")
}
console.log(Person)

Here Insert Picture Description

Relationship between structure and function, prototype object, an object instance of the three

var Person = function(name,age){
	this.name = name;
	this.age = age;
}
Person.prototype.eat = function(){
	console.log("吃饭")
}
var ws = new Person("小花",5)

Person constructor above example:
Here Insert Picture Descriptionexplain here what __proto__ and constructor function:
like every function has a prototype prototype objects, each object will have a __proto__, called the object prototype. It points to the prototype object constructor.
Whether prototype or __proto__ have a constructor function refers back to the constructor
can be seen from the chart:

console.log(Person.prototype.constructor === Person)    //true
console.log(ws.__proto__ === Person.prototype)          //true
console.log(ws.__proto__.constructor === Person)        //true

Prototype chain

Here Insert Picture DescriptionIt is seen from the figure:

console.log(Person.prototype.__proto__ === Object.prototype)    //true
console.log(Object.prototype.constructor === Object)            //true
console.log(Object.prototype.__proto__)                         //null

Find a rule object is to find members along the prototype chain

When accessing an object property or method:

  1. There is no first find the object itself, there are exits to find, or along the prototype chain lookup (__proto__ prototype prototype object points)
  2. Then find the prototype object constructor had not, there would withdraw find, or find along the prototype chain
  3. Look Object constructor prototype there is not, there exits Find otherwise find along the prototype chain until the end of NULL
Released five original articles · won praise 6 · views 69

Guess you like

Origin blog.csdn.net/qq_22841567/article/details/104611122