1. Introduction

About JS prototype and prototype chain I just learned JS before have written a study notes form of blog, but two days ago turned out a look – what ghost, this is I write? They do not understand, so I rearrange ideas, today “front-end material package” to bring the fourth.

Prototype and prototype chain is the difficult point in JS, there is a saying, do not understand the prototype and prototype chain, even if there is no real entry of the front end. And prototyping and prototyping chains can be a must-have topic in an interview. By the end of this post you will have a good understanding of prototypes and prototype chains. If you find this article helpful, please click 👍 on the left. Thank you 🙆

Function objects

All objects in JS are divided into function objects and ordinary objects. Any object created by new Function() is a Function object. Function objects have a Prototype attribute and a __proto__ attribute.

prototype

JS was originally designed to implement simple inheritance by introducing the Prototype property, also known as the prototype object (explicit prototype).

// Prototype objects
function Animal(){};  

console.log(typeof Animal.prototype) //Object  
console.log(typeof Object.prototype) // Object  
Copy the code

As you can see, Prototype is essentially a normal object, an instance created by the constructor of a function object. When Animal is created, it automatically creates an instance of it and assigns that instance to Prototype.

Function. Prototype = Function. Prototype = Function. As a function object, it has no prototype property.

console.log(typeof Function.prototype) / / special Function
console.log(typeof Function.prototype.prototype) // Undefined function object has no prototype property
Copy the code

__proto__ properties

All objects obj(except null and undefined) have a __proto__ attribute (implicit prototype). The __proto__ attribute is essentially a pointer to the prototype attribute of the function object.

// Create a constructor
        function Animal(name,age){
            this.name = name;
            this.age= age;
        }
        Animal.prototype = {
            alertName(){
                alert(this.name); }}// Create an instance
        var dog = new Animal("Rhubarb");
        dog .print = function(){
             alert(this.name);
        }
        dog.print();  / / rhubarb
        dog.alertName();  / / rhubarb

Copy the code

The print() method is the method dog instance itself has, so dog.print() prints “rhubarb”; AlertName () does not belong to the dog instance’s method, but to the constructor’s. Dog.alertname () also prints “rhubarb” because the dog instance inherits the constructor’s method.

In fact, the implicit prototype (__proto__) of instance dog points to the explicit prototype (prototype) of its constructor, which means equivalent to, i.e

dog.__proto__ === Animal.prototype// true
Copy the code

We can use a picture to help us understand memory

3. Constructor

As the name implies, the constructor constructor is used to construct a function object, and the constructor property returns a reference to the function object that created it. In plain English, this refers to the father of the current object

function Animal(){};
console.log(Animal.constructor===Function); //true
console.log(Animal.prototype.constructor===Animal); //true
Copy the code

Function of Animal is created by the Function, then its constructor to Function, Animal. The prototype is made by new Animal () created, then the Animal. The prototype. The constructor should point to Animal. Again, we use pictures to help us remember

Here’s a thought: animal.prototype. _proto_. Constructor points to who? Feel free to leave your answers in the comments section

4. The prototype chain

Prototype chain is the main method to implement inheritance in JS. The basic idea is to have one reference type inherit the properties and methods of another. Here are some of the most common combinations of inheritance

function Animal(){  
    this.animalType = "animal";  
}  
Animal.prototype.getAnimalType = function(){  
    return this.animalType ;  
}  

function Dog(){  
    this.Dogtype = "dog";  
}  
Dog.prototype = new Animal();  

Dog.prototype.getDogType = function(){  
    return this.Dogtype ;  
}  

var dahuang = new Dog();

alert(dahuang.getAnimalType ());// animal
Copy the code

Dahuang. GetAnimalType () prints animal. Dahuang doesn’t have a getAnimalType () method, so it looks in its _proto_ constructor. So follow the _proto_ upwards to find again, in Animal. Prototype. GetAnimalType found, return the result.

If it still doesn't exist in Animal, keep looking until the Object. Prototype Object ends

It is concluded that the prototype chain is composed of prototype objects, each object has a __proto__ attribute, pointing to the prototype of the constructor that created the object, __proto__ connects the objects to form the prototype chain. Is a finite chain of objects that implements inheritance and shared properties.

  • Attribute search mechanism: when searching for the attribute of an Object, if the instance Object itself does not exist, it will search up the prototype chain and output the attribute when it is found. If it does not exist, it will continue to search up the prototype chain until it reaches the top prototype Object. Prototype.
  • Attribute modification mechanism:Only the attributes of the instance object itself will be modified. If they do not exist, the attributes will be added. If you need to modify the attributes of the prototype, you can use:b.prototype.x = 2; This, however, causes the properties of all instances that inherit from the object to change.

5. What are the roles between prototype objects and prototype chains?

If there are a lot of properties and methods in the constructor, then all the instantiation object constructor is common these attributes and methods, when there are multiple instances to share these things, a copies of each instance and will cause great waste of resources, is that can consider to save these need common properties and methods on a common thing. That common thing is the prototype object.

Of course, there are also some problems in the implementation of prototype chain inheritance. The most important problems are that the prototype contains reference type and the parent constructor is called when the parent class function is inherited, resulting in more unnecessary parent class attributes on the prototype of the subclass, and there is a waste of memory. The second is that when creating instances of subtypes, arguments cannot be passed to the constructor of the supertype. The solution will be revealed in a follow-up article

The latter

JavaScript prototypes and prototype chains are really hard to understand, and it is said that even experienced drivers who have been working on them for a few years may not be able to get around them, but it is possible to use examples and drawings to help understand them. Finally, small is the front small white one, the most original intention of writing an article is to let oneself have a more profound impression and understanding of the knowledge point, write the thing is also very small white, if there is wrong, welcome to correct ~ then is the hope to see a friend can point like, can also pay attention to a wave ~ I will continue to output!

Personal Blog links

CSDN homepage

Nuggets personal homepage

Jane book personal home page