preface

Prototype, prototype chain should be the most front-end ER said bad word, but there should be a lot of people can not fully explain these two content, of course, including myself.

The first article of prototype chain was written in July 2019. At that time, it took a lot of effort to understand 70% or 80% of it, but now I have almost forgotten it. After a lapse of two years, the interest started to review the contents of the prototype and the prototype chain.

Objects in JavaScript

In JavaScript, an object is called a collection of properties.

There are several ways to create an object, the most common of which is in the form of double curly braces:

var obj = {};
obj.name = 'Little potato';
obj.age  = 18;
Copy the code

This is actually the syntactic sugar of the following:

var obj = new Object(a); obj.name ='Little potato';
obj.age  = 18;
Copy the code

In addition, you can customize objects in JavaScript through constructors.

function Cat(){}
var catMimi = new Cat();  // Custom objects
Copy the code

If a function is called with the new keyword, it is called a constructor; otherwise, it is a normal function.

What is a prototype

A quick summary of a prototype: A prototype is an object.

In a later summary, a stereotype may be described as a stereotype object, which is equivalent to a stereotype

Where do prototypes come from? Where does the prototype object exist, and does it need to be created in code?

When we say that an object is a collection of properties, what properties does the prototype object contain?

How to operate and use prototypes?

Let’s explore one question at a time.

Where do prototypes come from

JavaScript creates a prototype for all functions.

function Cat(){}
Copy the code

In the above code, we created a Cat function, which has a Cat prototype.

We also create a function called Fn1. Fn1 has a prototype, denoted in code as fn1.prototype.

There is essentially no difference between uppercase and lowercase function names

What attributes the stereotype contains

We said the following two points earlier:

  • A prototype is an object
  • An object is a collection of properties

So what attributes do stereotypes contain?

Functionname. prototype = functionname. prototype = functionname. prototype = functionname. prototype = functionname. prototype = functionname. prototype = functionname. prototype = functionname. prototype = functionname. prototype = functionname. prototype = functionname. prototype

function Cat(){}
console.log("Cat.prototype:");
console.log(Cat.prototype);

function Dog(){}
console.log("Dog.prototype:");
console.log(Dog.prototype);
Copy the code

The following output is displayed in Firefox:

You can see that a function’s prototype has two default attributes: constructor and .

Where, the constructor property of the function prototype points to the function itself.

The < propoType > attribute of a function stereotype is called an implicit stereotype, which we’ll cover in a separate section later.

How to operate and use prototypes

Normally we would operate on an ordinary object like this:

var obj = {};          // Create an object
obj.name = 'Little potato';    // Add attributes to the object
obj.age = 18;          // Add attributes to the object
var name = obj.name;   // Access object properties
Copy the code

Since the prototype is also an object, you manipulate the prototype in the same way as above.

function Cat(){}
Cat.prototype.type = 'cat';
Cat.prototype.color = 'White';
Cat.prototype.sayInfo = function(){
    console.log(this.type + ' is ' + this.color);
}
Copy the code

Print cat. prototype again to see the properties we added to the prototype:

Accessing methods and properties on the prototype object:

The above methods of working with prototypes are not useful for real project development, but don’t worry, we’ll cover them later. Right

Implicit stereotype

Implicit stereotypes were mentioned earlier when we summarized the prototype object of a function.

So, in fact, JavaScript creates properties called implicit stereotypes for all objects. We’ve always said that a prototype is an object, so in the screenshot above, the prototype also has an implicit prototype property.

Code representation of implicit stereotypes

An implicit stereotype is a private property of an object that can be accessed in code as obj.__proto__.

The obj.__proto__ notation is non-standard and is not supported by older browsers

Let’s actually access it in the browser console:

You can see from the printed result that the implicit stereotype is also an object. What properties does the implicit stereotype contain in the object? Let’s take a look.

The meaning of the existence of implicit archetypes

Let’s start with a simple example:

function Cat(){}
var catMimi = new Cat();
var catJuju = new Cat();
Copy the code

In the above code, we create a Cat function and two instance objects, catMimi and catJuju, with Cat as the constructor, using the new keyword.

Let’s take a look in the browser’s Console tool to see what attributes are included in the implicit stereotypes of both instance objects.

__proto__ and catjuju._proto__ appear to be the same, and eagleeyed students will have noticed that this print appears to be the same as the Cat. Prototype printed in the previous section.

Without further ado, let’s use the == operator to determine:

You can see that all values are true.

Since catMimi and catJuJu are instances of the Cat function, it is concluded that __proto__, the implicit prototype of the object, refers to the prototype of the function that created the object.

Prototype chains: The meaning of the existence of archetypes and implicit archetypes

We’ve summarized the concepts of stereotypes and implicit stereotypes and how to manipulate them with code. In general, it doesn’t seem like there’s much to be said about stereotypes and implicit stereotypes. What are they really good for?

All instance objects share properties and methods defined on the stereotype

Let’s look at the following example:

function Cat(name, age){
    this.type = 'RagdollCat';  / / ragdoll
    this.eyes = 2;
    this.name = name;
    this.age = age;
    this.sayInfo = function(){
        console.log(this.type + ' ' + this.name + ' is ' + this.age + ' years old'); }}Copy the code

In this example, we create a Cat function with five attributes: type, eyes, name, age, and sayInfo. The type and eyes attributes already have initial values, while name and age are passed and assigned as parameters. SayInfo corresponds to a function that prints the values of type, name, and age.

We then create two instance objects of Cat, catMimi and catJuju, passing in different name and age parameters.

var catMimi = new Cat('Mimi'.1);
var catJuju = new Cat('Juju'.2);
Copy the code

Console take a look at the object we created:

As you can see, these two objects have the same properties. Since the initial values of type and eyes are fixed when the Cat function is created, the values of these two properties are the same. The sayInfo function also does the same thing, printing information about some properties; Only name and age are passed as parameters, and their values are different. In addition, catMimi and catJuju are two different objects, and their property values are independent of each other. Changing the property value of either object does not affect the property value of the other object.

If we have more such objects later, JavaScript will still create the same attribute for each object, and all of these objects will have the same type, the same eyes attribute value, and the same sayInfo function. This is a waste of memory, so we can define these attributes on the prototype object of the function:

function Cat(name, age){
    this.name = name;
    this.age = age;
}

Cat.prototype.type = 'RagdollCat';    / / ragdoll
Cat.prototype.eyes = 2;
Cat.prototype.sayInfo = function(){
    console.log(this.type + ' ' + this.name + ' is ' + this.age + ' years old');
}
var catMimi = new Cat('Mimi'.1);
var catJuju = new Cat('Juju'.2);
Copy the code

Then let’s look at these two objects:

You can see that the two objects now contain only two properties, name and age, defined within the contents of the Cat constructor.

Then we access type, eyes, and sayInfo on the object:

Our instance object still has access to the properties, and the methods print the correct information. So how exactly is that accessed?

Prototype chain

In the previous example code, we defined some properties and methods on the prototype of the function. Finally, the instance object created using the function can access the properties and methods defined on the prototype. How does this work?

We said earlier that the implicit prototype of an object points to the prototype of the function that created the object, so when an instance object doesn’t have a property in it, JavaScript follows the implicit prototype of that instance object. This is what we call the prototype chain.

Since it’s a chain, we’re thinking of things connected to one another, so it’s not just the implicit prototype of the current instance object that points to the prototype of the function that created it, so we’re doing something with the catMimi object:

In the above operation, we called the hasOwnProperty method of catMimi. Obviously, we didn’t define the method for this object. So where does this method come from?

The answer, again, is the prototype chain:

  • callcatMimi.hasOwnProperty()methods
  • In the instance objectcatMimiThe attribute is not found in the
  • Go to thecatMimi.__proto__BecausecatMimi.__proto__=Cat.prototypeOf the instance objectImplicit stereotypePoints to the function that created the instanceThe prototype)Cat.prototypeLook forhasOwnPropertyProperties, obviouslyCat.prototypeIt also does not have that property
  • So I keep goingCat.prototype.__proto__Search, and becauseCat.prototype.__proto__ = Object.prototypeWe have been emphasizing that a prototype is an object, and since it is an object, it is defined byObjectFunction created, soCat.prototypetheImplicit stereotypePoint to theObjectFunction prototype)

Object. Prototype contains hasOwnProperty:

As you can see, the Object. The prototype in hasOwnProperty attribute, so catMimi. HasOwnPrototype actually call is Object. The prototype. The hasOwnProperty.

conclusion

This is the end of this article, and I believe you should have some understanding of prototypes and prototype chains. Finally, we are making a conclusion of this article.

A recent article

Explain computed and Watch in Vue

Remember a real Webpack optimization experience

JavaScript execution context is not as difficult as you might think

A preliminary study on Page – skeleton-webpack-Plugin

Vue with Django-rest-FrameWord

Vue with Django-rest-FrameWord

Write in the last

If this article has helped you, please follow ❤️ + like ❤️ and encourage the author

Article public number first, focus on unknown treasure program yuan for the first time to get the latest article

Ink ❤ ️ ~