Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What does the prototype and prototype chain of Javascript mean

2025-03-29 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

This article mainly introduces the meaning of the prototype and prototype chain of Javascript. It is very detailed and has certain reference value. Friends who are interested must finish it!

First, why use prototypes? How to understand the emergence of prototypes 1. The shortcomings of creating objects literally.

If we want to introduce prototypes, we have to mention why we use prototypes. In the early days of js, we created an object. It is more popular to use object literals to create an object, for example:

Const person = {name: "wywy", age: 21, hobby: "listen to Jay Chou"}

To create objects in this way, although simple and straightforward, but if we need to create a large number of such objects, like person, we may need to create multiple different people, then each time we need to declare to create, so the workload is huge, in order to solve this problem, we introduced the concept of factory function.

2. Factory function

What is a factory function? as its name implies, you can think of a factory function as an pipelined factory, which is used to mass produce person objects, such as the following:

Function createPerson (name,age,hobby) {const obj = {}; obj.name = name; obj.age = age; obj.hobby = hobby; return obj;} const person1 = createPerson ("zs", 23, "skateboard"); const person2 = createPerson ("ls", 22, "listen to music"); console.log (person1); console.log (person2)

Here, when we create a person object, we just need to call this function and pass in the property values corresponding to each object. This does simplify the amount of code compared to creating person one by one with the literal amount of objects, but the factory function also has its own shortcomings, that is, we cannot judge the type of this object and subdivide it according to the complex reference data types we know in js. There is Array,Function. String, etc., but these objects created through the factory function mode are all Object types printed on the console, if you have multiple factory functions and use multiple factory functions to create multiple instances, but you do not know which factory these objects belong to. For this reason, the concept of constructor is introduced.

3. Constructor

With regard to constructors, it is actually very similar to factory functions. There is no separate class of functions called constructors in js functions. Constructors are always used with the new keyword, or more accurately, a function is called by a constructor. When a constructor is called without the new keyword, it is no different from a normal function.

Function CreatePerson (name, age, hobby) {this.name = name; this.age = age; this.hobby = hobby;} const person1 = new CreatePerson ("zs", 23, "skateboard"); const person2 = new CreatePerson ("ls", 22, "listen to music"); console.log (person1); console.log (person2)

After careful observation, it is not difficult to find that we have made the following changes to the above factory function:

1. We capitalize the first letter of the function name. There is a rule in js that if you plan to use a function as a constructor in the future, it is best to capitalize its function name to remind the user that it is a constructor. In fact, there will be no grammatical errors if you don't capitalize.

2. We cancel the declaration of an object "const obj = {}" displayed inside the function, and cancel the operation "return obj" that finally returns the object.

3. The new keyword is added before calling the CreatePerson function.

Then we look at the result. At this time, the object we print is no longer Object, but the function CreatePerson that we created. It seems that the constructor does solve the problem that the object cannot determine the type.

So what does the magic new keyword do in the background? In fact, it did the following five things

1. Create a new object in memory.

2. Let the internal property of the new object [[Prototype]] save the property value of the prototype of the function CreatePerson, that is, save the pointer of the prototype of the function to [[Prototype]].

3. Point the this inside the function to the newly created object.

4. Execute the code inside the function.

5. If the function itself does not return an object, then return the new object.

We see that the constructor has done so much for us in the background. So is the constructor perfect? Not really. Do we think a person should also add a method to it? So let's add a way to speak:

Function CreatePerson (name, age, hobby) {this.name = name; this.age = age; this.hobby = hobby; / / add a method this.sayHi = function () {console.log ("Hello, my name is" + this.name ")} const person1 = new CreatePerson (" zs ", 23," skateboard "); const person2 = new CreatePerson (" ls ", 22," listen to music "); console.log (person1) Console.log (person2)

But we found that there is no doubt that this adds a sayHi method for each instance object, and the methods on each instance are not equal, but our goal is to make each instance have such a function, instead of creating so many sayHi methods to waste memory space. To put it bluntly, for example, if there are five children in the family and each child wants to play switch games, do parents want to buy a switch for each child? Of course, if there is a mine at home, I didn't say that most families just buy one, and then any child who wants to play can just care if the parents want it or not.

Similarly, code is an abstraction of real life, so can we do the same, add methods to a father that all these instances have, and think carefully about whether the second step in the five steps of new has done such a thing? yes, he is the prototype in js. This prototype is the father of these examples.

Having said so much, we are finally going to talk about the prototype!

II. Use the prototype

Through the above explanation, we seem to have a general understanding of the role of the prototype, which is to add the common methods that need to be used on the instance object to the prototype, while the instance object's own private properties are written inside the constructor.

Next, let's modify the constructor again:

Function CreatePerson (name, age, hobby) {this.name = name; this.age = age; this.hobby = hobby; / / add a method this.sayHi = function () {console.log ("Hello, my name is" + this.name ")} const person1 = new CreatePerson (" zs ", 23," skateboard "); const person2 = new CreatePerson (" ls ", 22," listen to music "); console.log (person1) Console.log (person2)

First of all, I tell you that I do not define a constructor, then add the sayHi method to the prototype of the constructor, and then write the code in the order in which the instances are created using new. Instead, new first creates the instance, and then adds the method to the prototype, which is to tell you that the prototype is dynamic, that is, you create the instance first, and add the method to the prototype after the instance, so that the instance is still accessible. And you can see that by comparing the sayHi methods of person1 and person2, we find that this is the same method. In this way, we solve the problem of constructor perfectly.

III. Discrimination of the concept of prototype

First of all, two concepts are clear:

Reference types, all with object properties, are free to extend properties. (reference type: Object, Array, Function, Date, RegExp)

Each function function has a display prototype prototype, and each instance object has an implicit prototype _ _ proto__

Function Fn () {/ / Internal statement: this.prototype = {}} / / 1, each function function has a prototype, that is, display prototype (attribute) console.log (Fn.prototype); / / 2, each instance object has a _ _ proto__, which can be called implicit prototype (attribute) var fn = new Fn (); / / Internal statement: this.__proto__ = Fn.prototypeconsole.log (fn.__proto__)

Two criteria:

Follow the following two guidelines when designing js prototype chains:

Rule 1: the constructor of the prototype object (that is, Fn.prototype) points to the constructor itself.

Rule 2: the _ _ proto__ of the instance object (that is, fn) points to the display prototype of its constructor.

Function Fn () {} var fn = new Fn (); / / the constructor of the prototype object points to the constructor itself console.log (Fn.prototype.constructor = Fn); / / the value of the implicit prototype of the true// object is the value of the display prototype of its corresponding constructor console.log (Fn.prototype = fn.__proto__); / / true

Understand Function and Object special cases

Each function is an instance of Function, so each function has both an explicit prototype and an implicit prototype, and the implicit prototype of all functions points to the Function.prototype; constructor Function. The constructor is itself.

/ / function Foo () {} is equivalent to var Foo = new Function () / / Function = new Function () = > Function.__proto__ = Function.prototype// Object as the constructor, its _ _ proto__ internal attribute value points to Function.prototype// Object.__proto__ = Function.prototype// Function.constructor=== Function;//true

The Object constructor creates an object wrapper. All objects in JavaScript come from Object, and all objects are instances of Object; all objects inherit methods and properties from Object.prototype, although they may be overridden.

/ / the prototype object (Fn.prototype) of Fn also comes from Object, so Fn.prototype.__proto__ = Object.prototypefunction Fn () {}

Prototype chain:

When you read the properties of an object, it automatically finds the lookup in the prototype chain.

1. Now look for it in your own attributes and return it.

2. If you can't find it, continue to search up the chain of _ _ proto__ and return it.

3. If not found in the end. When the property value of the undefined setting object is returned, the prototype chain is not found. If there is no such property in the current object, the method of directly adding this property and setting its value is generally defined in the prototype, and the property is generally defined in the object itself through the constructor.

The prototype chain is a process, and the prototype is a unit in the process, which runs through the whole prototype chain.

Graphic illustration

4. Prototype chain exercise / / exercise 1function A () {} A.prototype.n = 1 2var var b = new A (); A.prototype = {nObject.prototype.a 2, MRAR 3} var c = new A (); console.log (b.nlue b.mlue c.n.c.m) / / 1 undefined 23 hand / test question 2var F = function () {}; Object.prototype.a = function () {console.log ('a ()');} Function.prototype.b = function () {console.log ('b ()';}; var f = new F (); f.a (); / a () f.b (); / / error report: Uncaught TypeError: f.b is not a functionF.a (); / a () F.B (); / / b ()

The meaning and usage scenario of prototype, prototype chain:

The function of the prototype object is to store the common properties and methods in the instance, which can greatly reduce the memory consumption.

The above is all the content of the article "what is the meaning of the prototype and prototype chain of Javascript". Thank you for reading! Hope to share the content to help you, more related knowledge, welcome to follow the industry information channel!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 287

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report