In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-03-26 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/01 Report--
Editor to share with you how to use JavaScript to achieve inheritance, I believe that most people do not know much about it, so share this article for your reference, I hope you can learn a lot after reading this article, let's go to know it!
First, background introduction
JavaScript is a special category in the programming language world. Unlike other programming languages, JavaScript can dynamically change the type of a variable at run time.
For example, you can never imagine how many types a variable like isTimeout can have. In addition to the Boolean values true and false, it may also be undefined, 1 and 0, a timestamp, or even an object.
If the code runs abnormally, open the browser, start breakpoint debugging, and find that the variable InfoList is an array when it is first assigned:
[{name: 'test1', value:' 11'}, {name: 'test2', value:' 22'}]
After a while, he became an object:
{test1:'11', test2: '22'}
In addition to variables that can be assigned to any type at run time, inheritance can also be implemented in JavaScript, but instead of class-based inheritance like Java, C++, and C #, it is based on prototypes.
This is because there is a special presence in JavaScript: objects. Each object also has a prototype object from which you can inherit methods and properties.
When it comes to objects and prototypes, there are the following questions:
Why is the function of JavaScript also an object?
What exactly is the relationship between proto and prototype?
How do objects inherit in JavaScript?
How does JavaScript access the methods and properties of an object?
II. The relationship between prototype objects and objects
In JavaScript, an object consists of one or more sets of properties and values:
{key1: value1, key2: value2, key3: value3,}
In JavaScript, an object has a wide range of uses because its values can be primitive types (number, string, boolean, null, undefined, bigint, and symbol) as well as objects and functions.
Whether they are objects, functions, and arrays, they are all instances of Object, that is, in JavaScript, except for primitive types, they are all objects.
This also answers the question why the function of 1:JavaScript is also an object.
In JavaScript, a function is also a special object that also has properties and values. All functions have a special property, prototype, whose value is an object, which is what we often call a "prototype object".
We can print this property on the console:
Function Person (name) {this.name = name;} console.log (Person.prototype)
The print result is shown as follows:
As you can see, the prototype object has two properties: constructor and proto.
At this point, we seem to wonder, "what is the relationship between 2:proto and prototype?" The answer is about to appear. In JavaScript, the proto property points to the prototype object of the object, and for functions, its prototype object is prototype.
The prototype object of the function, prototype, has the following characteristics:
By default, the prototype object (prototype) of all functions has a constructor property that points to the constructor associated with it, which in this case is the Person function
The prototype object (prototype) of the Person function also has its own prototype object, represented by the proto property. As mentioned earlier, the function is an instance of Object, so the prototype object of Person.prototype is Object.prototype.
We can use this diagram to describe the relationship between the three attributes prototype, proto, and constructor:
From this diagram, we can find this relationship:
In JavaScript, the proto property points to the prototype object of the object
For a function, each function has a prototype property, which is the prototype object of the function
Second, use prototype and proto to realize inheritance
Objects are widely used because the property values of objects can be of any type. Therefore, the value of the property can also be another object, which means that JavaScript can do this by assigning the proto property of object A to object B, that is:
A. crude protozoa _ = B
At this point, you can access the properties and methods of B using A.proto.
In this way, JavaScript can create an association between two objects so that one object can access the properties and methods of another object, thus implementing inheritance
Third, use prototype and proto to realize inheritance
Take Person as an example. When we create an object using new Person (), JavaScript creates an instance of the constructor Person. For example, here we create a Person called "zhangsan":
Var zhangsan = new Person ("zhangsan")
When the above code is running, the JavaScript engine implements zhangsan's inheritance of Person by assigning the prototype object prototype of Person to the proto property of instance object zhangsan, that is, executing the following code:
/ / the JavaScript engine executed the following code var zhangsan = {}; zhangsan.__proto__ = Person.prototype;Person.call (zhangsan, "zhangsan")
Let's print an example of zhangsan:
Console.log (zhangsan)
The result is shown in the following figure:
As you can see, zhangsan is an instance object of Person, and its proto points to the prototype object of Person, namely Person.prototype.
At this point, let's add the relationship in the image above:
From this diagram, we can clearly see the relationship between constructors and constructor properties, prototype objects (prototype) and proto, instance objects, which is easy to be confused. According to this picture, we can get the following relationships:
The prototype object (Person.prototype) of each function has a constructor property that points to the constructor (Person) of the prototype object.
Use the constructor (new Person ()) to create an object called an instance object (lily)
The instance object implements the inheritance of the prototype object by pointing the proto property to the prototype object (Person.prototype) of the constructor.
So now, about the relationship between proto and prototype, we can get the following answer:
Each object has a proto attribute to identify the prototype object it inherits, but only a function has a prototype property
For a function, each function has a prototype property, which is the prototype object of the function
Inheritance can be achieved by assigning the proto property of the instance object to the prototype object prototype,JavaScript whose constructor is used to create the object.
So an object can access the properties and methods on the prototype object through proto, and the prototype can also access its prototype object through proto, so we construct a prototype chain between the instance and the prototype. The red line shows:
Access to the methods and properties of an object through a prototype chain
When JavaScript tries to access the properties of an object, it looks based on the prototype chain. The search process goes like this:
The first priority is to search on the object. If it cannot be found, it will also search for the prototype object of the object, the prototype object of the prototype object, and so on (nesting doll alarm).
All objects in JavaScript come from Object,Object.prototype.proto = null. Null does not have a prototype and is the last link in the prototype chain
JavaScript traverses the entire prototype chain of the access object, and if it is still not found in the end, the property value of the object is assumed to be undefined.
We can represent the access process of object properties based on prototype chain through a concrete example, in which we build a prototype chain of objects and access property values:
Var o = {a: 1, b: 2}; / / Let's assume that we have an object with its own attributes an and bgho.protoplast _ = {b: 3, c: 4}; / o's prototype o.protoplast _ has attributes b and c:
When we get the property value, we trigger the lookup of the prototype chain:
Console.log (o.a); / / o.a = > 1console.log (o.b); / / o.b = > 2console.log (o.c); / / o.c = > o.__proto__.c = > 4console.log (o.d); / / o.c = > o.__proto__.d = > o.o.protozoa = = null = > undefined
To sum up, the whole prototype chain is as follows:
{aRV 1, bRV 2}-> {BRV 3, CRAV 4}-> null, / / this is the end of the prototype chain, that is, null
As you can see, when we get the attribute value of an object, the prototype chain lookup process of the object is triggered.
Since JavaScript accesses the properties of the object by traversing the prototype chain, we can inherit it through the prototype chain.
That is, the properties and methods on the prototype object can be accessed through the prototype chain, and we do not need to reassign / add methods to the object when it is created. For example, when we call lily.toString (), the JavaScript engine does the following:
First check whether the lily object has an available toString () method
If not, ``checks whether the prototype object (Person.prototype) of lily has an available toString () method
If not, the prototype object (that is, Object.prototype) of the object pointed to by the prototype property of the Person () constructor is checked for an available toString () method, and the method is called.
Because the property search through the prototype chain requires traversing each prototype object layer by layer, it may cause performance problems:
When trying to access properties that do not exist, the entire prototype chain is traversed
Finding attributes on the prototype chain is time-consuming and has side effects on performance, which is important in situations where performance requirements are demanding.
Therefore, when designing objects, we need to pay attention to the length of the prototype chain in the code. When the prototype chain is too long, you can choose to decompose to avoid possible performance problems.
5. Other ways to realize inheritance
In addition to implementing JavaScript inheritance through prototype chains, the ways to implement inheritance in JavaScript include classical inheritance (embezzling constructors), combinatorial inheritance, prototypic inheritance, parasitic inheritance, and so on.
In the prototype chain inheritance mode, the properties of the reference type are shared by all instances, so the instance cannot be private.
The classical inheritance method can realize the private property of the instance, but requires that the type can only be defined through the constructor.
Composite inheritance combines the advantages of prototype chain inheritance and constructors, and its implementation is as follows:
Function Parent (name) {/ / private attribute, do not share this.name = name;} / / methods that need to be reused and shared are defined on the parent class prototype Parent.prototype.speak = function () {console.log ("hello");}; function Child (name) {Parent.call (this, name);} / inheritance method Child.prototype = new Parent ()
The combined inheritance pattern realizes on-demand sharing objects and methods by defining shared attributes on the parent class prototype and assigning private attributes through constructors, which is the most commonly used inheritance pattern in JavaScript.
Although there are many ways to realize inheritance, they are actually inseparable from the content of prototype object and prototype chain, so mastering the knowledge of proto and prototype, object inheritance and so on is the prerequisite for us to realize all kinds of inheritance.
The above is all the contents of the article "how to use JavaScript to achieve inheritance". Thank you for reading! I believe we all have a certain understanding, hope to share the content to help you, if you want to learn more 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: 0
*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.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.