In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-17 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
Today, I would like to share with you the relevant knowledge of what the role of javascript inheritance is, detailed content and clear logic. I believe most people still know too much about this knowledge, so share this article for your reference. I hope you can get something after reading this article. Let's take a look at it.
The role of javascript inheritance: 1, you can not call the constructor of the "parent class" to create new instances; 2, modify the "parent class" prototype can dynamically modify all the instances that have been created; 3, you can dynamically modify the prototype of an object.
The operating environment of this tutorial: windows7 system, javascript1.8.5 version, Dell G3 computer.
JavaScript is an object-oriented development pattern based on object, function as model and prototype as inheritance.
The role of javascript inheritance:
1. You can create a new instance without calling the constructor of the "parent class"
2. Modify the prototype of the "parent class" to dynamically modify all the created instances
3. The prototype of an object can be modified dynamically, that is to say, parents can change it.
The following describes the methods for defining JavaScript types and common patterns for implementing inheritance.
Construction prototype
There are two problems with designing class inheritance directly using prototype prototypes.
Because the constructor is declared in advance, and the prototype property is defined after the class structure declaration, parameters cannot be dynamically passed to the prototype through the constructor. In this way, the instantiated objects are all the same and have no personality. If you want to change the prototype property value, all instances will be disturbed.
When the value of a prototype property is reference type data, if the property value is modified in an object instance, all instances will be affected.
Example 1
Simply define the Book type and then instantiate it.
Function Book () {}; / / declare constructor Book.prototype.o = {x: 1, y: 2}; / / prototype property of constructor o is an object var book1 = new Book (); / / instantiate object book1var book2 = new Book (); / / instantiate object book2console.log (book1.o.x); / / return 1console.log (book2.o.x); / / return 1book2.o.x = 3 / / modify the value console.log (book1.o.x) of attribute x in the instantiated object book2; / / return 3console.log (book2.o.x); / / return 3
Because the prototype property o is a reference value, the value of the property o of all instances is a reference to the same object. once the value of o changes, it will affect all instances.
The construction prototype is a kind of hybrid design pattern which is born to solve the prototype pattern, which mixes the constructor pattern with the prototype pattern, so as to avoid the above problems.
Implementation: for prototype properties that may affect each other, and you want to pass parameters dynamically, you can design them independently using the constructor pattern. For methods or properties that do not require personalized design and have commonalities, you can use prototype patterns to design.
Example 2
Following the above design principles, two of the attributes are designed as constructor patterns, and the design method is prototype patterns.
Function Book (title, pages) {/ / Constructor pattern design this.title = title; this.pages = pages;} Book.prototype.what = function () {/ / prototype pattern design console.log (this.title + this.pages);}; var book1 = new Book ("JavaScript programming", 160); var book2 = new Book (C language programming, 240); console.log (book1.title); console.log (book2.title)
Constructing prototype patterns is the recommended standard for ECMAScript to define classes. It is generally recommended to use the constructor pattern to define all properties and the prototype pattern to define all methods. In this way, all methods are created only once, and each instance can set property values as needed. This is also one of the most widely used design patterns.
Dynamic prototype
According to the principle of object-oriented design, all members of a type should be encapsulated in the class structure. For example:
Function Book (title, pages) {/ / Constructor pattern design this.title = title; this.pages = pages; Book.prototype.what = function () {/ / prototype pattern design, located inside the class console.log (this.title + this.pages);};}
However, when instantiating each time, the prototype methods contained in the class Book will be created repeatedly, generating a large number of prototype methods and wasting system resources. You can use if to determine whether a prototype method exists, and if so, it is no longer created, otherwise it is created.
Function Book (title, pages) {this.title = title; this.pages = pages; if (typeof Book.isLock = = "undefined") {/ / create the lock of the prototype method, if it does not exist, create Book.prototype.what = function () {console.log (this.title + this.pages);}; Book.isLock = true / / after creating the prototype method, lock the lock to avoid repeated creation}} var book1 = new Book ("JavaScript programming", 160); var book2 = new Book ("C language programming", 240); console.log (book1.title); console.log (book2.title)
The typeof Book.isLock expression can detect the type of the property value, and if returned as a undefined string, the property value does not exist, indicating that there is no prototype method created, and allows the prototype method to be created, setting the value of the property to true, so that the prototype method does not have to be created repeatedly. The class name Book is used here instead of this because the prototype belongs to the class itself, not to the object instance.
Dynamic prototype pattern and construction prototype pattern are equivalent in performance, and users can choose freely, but the construction prototype pattern is widely used.
Factory model
The factory pattern is the most basic way to define types, and it is also one of the most commonly used development patterns in JavaScript. It simply encapsulates the instantiation of the object in a function, and then calls the function to achieve rapid and mass production of instance objects.
Example 1
The following example designs a Car type: contains three attributes: car color, number of driving wheels, and fuel consumption of 100 kilometers, and defines a method to display the car color.
Function Car (color, drive, oil) {/ / Automotive var _ car = new Object (); / / temporary object _ car.color = color; / / initialization color _ car.drive = drive; / / number of initialization drive wheels _ car.oil = oil / / initialize 100km fuel consumption _ car.showColor = function () {/ / method, prompt car color console.log (this.color);}; return _ car; / / return instance} var car1 = Car ("red", 4,8); var car2 = Car ("blue", 2,6); car1.showColor (); / / output "red" car2.showColor (); / / output "blue"
The above code is a simple factory pattern type, using the Car class can quickly create multiple car instances, their structure is the same, but the properties are different, you can initialize different colors, number of driving wheels and 100 km fuel consumption.
Example 2
In a type, a method is a behavior or operation that can complete a specific task according to initialization parameters and has something in common. Therefore, you can consider putting the method outside the Car () function to avoid creating a function every time you instantiate so that each instance shares the same function.
Function showColor () {/ / Public method prompts the car color console.log (this.color);}; function Car (color, drive, oil) {/ / Automobile var _ car = new Object (); / / temporary object _ car.color = color; / / initialize color _ car.drive = drive; / / initialize the number of drive wheels _ car.oil = oil / / initialize 100km fuel consumption _ car.showColor = showColor; / / refer to the external function return _ car; / / return the instance}
In the rewritten code above, the function showColor () is defined before the function Car (). Inside Car (), you avoid creating a new function each time you instantiate by referencing the external showColor () function. Functionally, this solves the problem of repeatedly creating a function; but semantically, the function is less like an object method.
Class inheritance
The design method of class inheritance is to call the parent class constructor in the subclass.
To implement class inheritance in JavaScript, you need to pay attention to the following three technical issues.
In the subclass, the parent class is called using apply, passing the parameters of the subclass constructor to the parent constructor. Let the subclass inherit the private property of the parent class, that is, Parent.apply (this, arguments); lines of code.
Create a prototype chain between the parent class and the subclass, that is, Sub.prototype = new Parent (); lines of code. This ensures that the parent and child classes are subordinate on the prototype chain, that is, the prototype of the child class points to an instance of the parent class.
Restores the constructor of the prototype object of the subclass, that is, the Sub.prototype.constructor=Sub; statement line. When you change the prototype prototype, the original constructor pointer is broken, so the constructor must be reset.
Example 1
The following example shows a case of triple inheritance, including base class, parent class, and subclass, which inherit step by step.
/ / Base class Basefunction Base (x) {/ / Constructor Base this.get = function () {/ / Private method, get the parameter value return x;}} Base.prototype.has = function () {/ / prototype method, determine whether the return value of the get () method is 0 return! (this.get () = = 0);} / / parent class Parentfunction Parent () {/ / constructor Parent var a = []; / private array an a = Array.apply (a, arguments); / / convert parameters to array Base.call (this, a.length) / / call the Base class and pass the parameter array length to it this.add = function () {/ / private method, add the parameter array to array an and return return a.push.apply (a, arguments)} this.geta = function () {/ / private method, return array a return a;}} Parent.prototype = private method () / / set the Parent prototype to the instance of Base, establish the prototype chain Parent.prototype.constructor = Parent; / / restore the constructor Parent.prototype.str = function () {/ / prototype method of the Parent class prototype object, convert the array to a string and return return this.geta (). ToString ();} / subclass Subfunction Sub () {/ / constructor Parent.apply (this, arguments) / / call the Parent class and pass it this.sort = function () {/ / private method to sort the array in character order var a = this.geta (); / / get the value of the array a.sort.apply (a, arguments); / / call the array sorting method sort () to sort the array} Sub.prototype = new Parent () / / set the Sub prototype to the Parent instance, establish the prototype chain Sub.prototype.constructor = Sub; / / restore the constructor of the Sub class prototype object / / the instance of the parent class Parent inherits the member of the Base class var parent = new Parent (1, 2, 3, 4); / / instantiate the Parent class console.log (parent.get ()); / / return 4, call the method get () console.log (parent.has ()) of the Base class / / return true, call the method has () of the Base class / / instance inheritance class Parent of the subclass Sub and member of the class Base var sub = new Sub (30, 10, 10, 20, 40); / / instantiate the Sub class sub.add (6, 5); / / call the Parent method add (), add the array console.log (sub.geta ()); / / return the array 30, 10, 10, 20, 40, 6, 5, sub.sort (); / sort the array console.log (sub.geta ()) / / return an array of 10 get () console.log (sub.has ()); / / return 4, call the method get () console.log (sub.has ()) of class Base; / / return true, call method has () console.log (sub.str ()) of class Base; / / return 10, 20, 30, 40, 5, 5, and 6
[design ideas]
The child class Sub inherits the parent class Parent, and the parent class Parent inherits the base class Base. The inheritance relationship between the Base, Parent, and Sub classes is maintained by the constructor called in the subclass.
For example, in the Sub class, Parent.apply (this, arguments); can call the parent class in the subclass and pass the parameters of the subclass to the parent class, so that the subclass has all the attributes of the parent class.
Similarly, in the parent class, Base.call (this, a.length); passes the parameter length of the parent class as a value to the base class and makes the call, thus realizing that the parent class has all the members of the base class.
From the perspective of inheritance relationship, the parent class inherits the private method get () of the base class, and in order to ensure that it can inherit the prototype methods of the base class, we also need to establish a prototype chain for them, so as to realize the inheritance relationship of the prototype object by adding the statement line Parent.prototype=new Base ();.
Similarly, add the statement Sub.prototype=new Parent () to the subclass, so that the base class, the parent class, and the subclass can be concatenated through the prototype chain, so that the subclass can inherit the properties of the parent class as well as the properties of the base class.
Example 2
Let's try to encapsulate the class inheritance pattern in order to standardize the code application.
Function extend (Sub, Sup) {/ / class inherits encapsulation function var F = function () {}; / / defines an empty function F.prototype = Sup.prototype; / / sets the prototype of the empty function as the prototype of the parent class Sub.prototype = new F (); / / instantiates the empty function and passes the parent prototype reference to the child class Sub.prototype.constructor = Sub / / the constructor to restore the subclass prototype Sub.sup for the subclass itself Sub.sup = Sup; / / define a private attribute to store the parent stereotype in the subclass / / check whether the parent prototype constructor is its own if (Sup.prototype.constructor = = Object.prototype.constructor) {Sup.prototype.constructor = Sup; / / Class inheritance encapsulated function}}
[procedure]
1) define an encapsulated function. The design entry is a subclass and a parent object, and the function function is that the subclass can inherit all the prototype members of the parent class without involving exits.
Function extend (Sub, Sup) {/ / classes inherit encapsulated functions / / where the parameter Sub represents the subclass and Sup represents the parent class}
2) in the body of the function, an empty function F is defined to realize the function transfer. The prototype is designed as the prototype of the parent class, and then the instance of the empty function is passed to the prototype of the subclass, thus avoiding the system load that may be caused by directly instantiating the parent class. Because in actual development, the size of the parent class may be large, and if instantiated, it will take up a lot of memory.
3) the constructor for restoring the subclass prototype is the subclass itself. At the same time, check whether the parent prototype constructor is coupled with the Object prototype constructor. If so, its constructor is restored to the parent class itself.
Let's define two classes and try to bind them as inheritance relationships.
Function A (x) {/ / Constructor A this.x = x; / / Private attribute x this.get = function () {/ / Private method get () return this.x;}} A.prototype.add = function () {/ / prototype method add () return this.x + this.x;} A.prototype.mul = function () {/ / prototype method mul () return this.x * this.x } function B (x) {/ / Constructor B A.call (this.x); / / call constructor An in the function body to implement internal data binding} extend (B, A); / / call encapsulation function to bind the prototypes of An and B together var f = new B (5); / / instantiate class Bconsole.log (f.get ()) / / inherit class A's method get (), return 5console.log (f.add ()); / / inherit class A's method add (), return 10console.log (f.mul ()); / / inherit class A's method mul (), return 25
In the function class encapsulation function, there is a sentence called Sub.sup=Sup.prototype;, that is not used in the above code, so what does it do? To answer this question, take a look at the following code.
Extend (B, A); B.prototype.add = function () {/ / define a prototype method return this.x + "" + this.x;} for class B
The above code defines a prototype method for class B after calling the wrapper function, which has the same name as the prototype method add () in the base class, but with different functions. If you test the program at this point, you will find that the prototype method add () defined by subclass B will override the prototype method add () of parent class A.
Console.log (f.add ()); / / returns the string 55 instead of the numeric value 10
If the prototype method add () of the parent class is called in the prototype method add () of class B, code coupling can be avoided.
B.prototype.add = function () {/ / define the prototype method add () return B.sup.add.call (this) of subclass B; / / call the parent method add () inside the function. That's all about the article "what is the purpose of javascript inheritance?" Thank you for reading! I believe you will gain a lot after reading this article. The editor will update different knowledge for you every day. If you want to learn more knowledge, please pay attention to 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.