Home > Web Front-end > JS Tutorial > How to understand the javascript prototype chain

How to understand the javascript prototype chain

醉折花枝作酒筹
Release: 2023-01-07 11:44:26
Original
1821 people have browsed it

The prototype chain is actually a limited chain between limited instance objects and prototypes, which is used to implement shared properties and inheritance. There are two main problems: 1. It is inconvenient to pass parameters to the parent type; 2. The reference type in the parent type is shared by all instances.

How to understand the javascript prototype chain

The operating environment of this tutorial: windows7 system, javascript version 1.8.5, Dell G3 computer.

What exactly does the new operator do? It’s actually very simple, it does three things.

var obj  = {};
obj.__proto__ = Base.prototype;
Base.call(obj);
Copy after login

In the first line, we create an empty object obj

In the second line, we point the __proto__ member of this empty object to the Base function object prototype member object

In the third line, we replace the this pointer of the Base function object with obj, and then call the Base function. So we assign an id member variable to the obj object. The value of this member variable is "base". About the call function usage.

Before talking about the prototype chain, we must first understand what is the relationship between custom functions and Functions, and what are the inextricable relationships between constructors, prototypes and instances? In fact, all functions are instances of Function. There is a prototype attribute prototype on the constructor, which is also an object; then there is a constructor attribute on the prototype object, which points to the constructor; and there is a _proto_ attribute on the instance object, which also points to the prototype. Object, and this property is not a standard property and cannot be used in programming. This property is used internally by the browser.

// _proto_
在函数里有一个属性prototype
由该函数创建的对象默认会连接到该属性上
    //prototype 与 _proto_ 的关系
_proto_是站在对象角度来说的
prototype 是站在构造函数角度来说的
Copy after login

Next, let’s look at the pictures to speak.

1. The relationship between constructor, prototype and instance

① Object

## ② Function Object Array

After understanding this, let’s discuss what a prototype chain is. To put it bluntly, it is actually a limited chain formed between limited instance objects and prototypes, which is used to implement shared properties and inheritance. Next, let’s look at the code.

 var obj = new Object();
对象是有原型对象的
原型对象也有原型对象
   obj._proto_._proto_._proto_
原型对象也有原型对象,对象的原型对象一直往上找,会找到一个null
// 原型链示例
   var arr = [];
   arr -> Array.prototype ->Object.prototype -> null
   var o = new Object();
   o -> Object.prototype -> null;
Copy after login
function Foo1(){
   this.name1 = '1';
}
function Foo2(){
   this.name2 = '2';
}
Foo2.prototype = new Foo1();
function Foo3(){
   this.name = '3';
}
Foo3.prototype = new Foo2();
var foo3 = new Foo3();
console.dir(foo3);
Copy after login

The next step is inheritance.

2. Inheritance

 1) Prototypal inheritance

function Animal(name){
       this.name = name;
   }
   function Tiger(color){
       this.color = color;
   }
//   var tiger = new Tiger('yellow');
//   console.log(tiger.color);
//   console.log(tiger.name);  //undefined
//      Tiger.prototype = new Animal('老虎');   //一种方式
   Object.prototype.name = '大老虎';   //第二种方式
        var tiger = new Tiger('yellow');
        console.log(tiger.color);
        console.log(tiger.name);
Copy after login

It is worth noting that there are two main problems here: ① It is inconvenient to pass parameters to the parent type; ②The reference type in the parent type is shared by all instances


2) ES5 provides the Object.create() method to implement inheritance

————做兼容
  //shim垫片
    function create(obj){
        if(Object.create){
            return Object.create(obj);
        }else{
            function Foo(){}
            Foo.prototype = obj;
            return new Foo();
        }
    }
Copy after login

This method is new to ES5 Features are actually copy inheritance.

3) Copy inheritance

var obj = {};
obj.extend = function(obj){
    for(var k in obj){
      this[k] = obj[k];
    }
}
Copy after login

4) Borrowed constructor inheritance

——The prototype members in the borrowed constructor have not been borrowed

function Animal(name){
    this.name = name;
}
function Mouse(nickname){
    Animal.call(this,'老鼠');
    this.nickname = nickname;
}
var m = new Mouse('杰瑞');
console.log(m.name);
console.log(m.nickname);
Copy after login

Existing problems: The parameter passing problem in prototypal inheritance can be solved, but the members (properties and methods) on the prototype object in the parent type cannot be inherited to

5) Combination inheritance

——The prototype object is dynamic

function Person(name){
   this.name = name;
}
Person.prototype.showName = function(){
   console.log(this.name);
}
function Student(name,age){
   Person.call(this,name);
   this.age = age;
}
Student.prototype = new Person();
Student.prototype.contructor = Student;
Student.prototype.showAge = function(){
    console.log(this.age);
}
var stu = new Student('张三',12);
stu.showName();
stu.showAge();
Copy after login
[Prototype inheritance borrows constructor inheritance] Its characteristic is that each instance has one copy of the attributes and shared methods

[Summary] It is very crude to apply a sentence In other words, the so-called prototype chain is a way of looking for a mother. It can be understood that humans are born from human mothers, and monsters are born from monsters. There is actually only one core of the prototype chain: attribute sharing and independent control. When your object instance requires independent attributes, the essence of all methods is to create attributes in the object instance. If you don't think too much, you can directly define the independent attributes you need in Person to override the prototype attributes. In short, when using prototypal inheritance, you must pay special attention to the attributes in the prototype, because they all affect the whole body. The most commonly used method now is the combined mode.

1. Prototype chain

1) The relationship between constructor, prototype and instance

①The constructor has an attribute prototype, which is an object (an instance of Object )

    ② There is a constructor attribute in the prototype object prototype, which points to the constructor function to which the prototype object belongs

    ③ Instance objects have a _proto_ attribute, which also points to the constructor function Prototype object, it is a non-standard attribute and cannot be used for programming. It is used by the browser itself

2) The relationship between prototype and _proto_

①Prototype is the constructor The attributes

②_proto_ is the attribute of the instance object

—This two points to the same object

[Summary] i) Function is also an object. The object is not necessarily the function; Collection of value pairs; the value in the key-value pair can be a value of any data type

        iii) The object is a container, and this container contains (properties and methods)

3) Attributes Search

①When accessing a member of the object, it will first search whether it exists in the object

②If it does not exist in the current object, it will search in the prototype object of the constructor

③ If the prototype is not found in the prototype object, find the prototype of the prototype object

④ Knowing the prototype of Object's prototype is NULL

2, Function

## - —All functions are instances of Function

①Local objects: objects independent of the host environment (browser) - including Object, Array, Date, RegExp, Function, Error, Number, String, Boolean

②Built-in objects - including Math, Global (window, global variables in js), no need to use new

③Host objects - including custom objects, DOM, BOM

[Recommended learning:

javascript advanced tutorial

]

The above is the detailed content of How to understand the javascript prototype chain. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template