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

Example Analysis of implementing inheritance in javascript

2025-02-14 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

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

Editor to share with you the example analysis of the implementation of inheritance in javascript. I hope you will get something after reading this article. Let's discuss it together.

Classlike inheritance / / declare parent class / / declare parent class function SuperClass () {this.superValue = true;} / / add common method SuperClass.prototype.getSuperValue = function () {return this.superValue;} for parent class; / / declare subclass function SubClass () {this.subValue = false;} / / inherit parent class SubClass.prototype = new SuperClass (); / / add common method SubClass.prototype.getSubValue = function () {return this.subValue;} for subclass Var instance = new SubClass (); console.log (instance.getSuperValue ()); / / trueconsole.log (instance.getSubValue ()); / / false type inheritance requires an instance of the parent class to be assigned to the child class prototype, and subClass.prototype inherits superClass. This type of inheritance has two disadvantages. First, because the subclass instantiates the parent class through the prototype prototype and inherits the parent class, if the common attribute in the parent class refers to the type, it will be shared by all instances in the subclass, so the instance of a subclass changes the common property inherited by the subclass prototype from the parent class constructor will directly affect other subclasses. As follows: function SuperClass () {this.courses = ['Chinese', 'Mathematics', 'English']} function SubClass () {} SubClass.prototype = new SuperClass () Var instance1 = new SubClass () var instance2 = new SubClass () console.log (instance2.courses) / / ['Chinese', 'Mathematics', 'English'] instance1.courses.push ('Chemistry') console.log (instance2.courses) / / ['Chinese', 'Mathematics', 'English', 'Chemistry'] the modification of instance1 directly affects instance2, which is a disaster trap. Second, because the inheritance of the subclass implementation is realized by the instantiation of the parent class by its prototype prototype, it is impossible to pass parameters to the parent class when creating the parent class, and the properties in the parent class constructor cannot be initialized when the parent class is instantiated. How to solve this problem? Please read on. The constructor inherits function SuperClass (current) {this.courses = ["Chinese", "mathematics", "English"]; this.current = current;} / / parent declaration prototype method SuperClass.prototype.getCourses= function () {console.log (this.courses);}; / / declare subclass function SubClass (current) {SuperClass.call (this, current);} var instance1 = new SubClass ("Chinese"); var instance2 = new SubClass ("mathematics") Instance1.courses.push (Chemistry) console.log (instance1.courses); / [Chinese, Mathematics, English, Chemistry] console.log (instance1.current); / / Chinese console.log (instance2.courses); / / [Chinese, Mathematics, English] console.log (instance2.current) / / Mathematical instance1.getCourses () / / TypeError: instance1.getCourses is not a functionSuperClass.call (this, current) this statement is the essence of constructor inheritance. Because the call method can change the environment of the function, calling the call on SuperClass in the subclass executes the variables in the subclass once in the parent class, and because the parent class binds the properties to the this, the subclass inherits the common properties of the parent class. Because this type of inheritance does not involve the prototype prototype, the prototype method of the parent class will not be inherited by the subclass. If you want to inherit by the subclass, you can only put the showCourse in the parent class constructor, but this violates the principle of code reuse. In order to combine the advantages of the above two kinds of inheritance, there is combinatorial inheritance. Combinatorial inheritance / / Combinatorial inheritance function SuperClass (current) {/ / reference types share attributes this.courses = ["Chinese", "Mathematics", "English"]; / / value types share attributes this.current = current;} SuperClass.prototype.getCourses = function () {console.log (this.courses);}; SuperClass.prototype.getCurrent = function () {console.log (this.current);} / / declare that the subclass function SubClass (current, time) {/ / the constructor inherits the parent class attribute SuperClass.call (this, current); this.time = time;} / / inherits the parent class SubClass.prototype = new SuperClass (); / / the subclass prototype method SubClass.prototype.getTime = function () {console.log (this.time);} The parent class constructor is executed in the subclass constructor. Instantiating the parent class on the subclass prototype is the combination pattern. Changing the reference type property courses inherited by the parent class in the subclass instance does not change the other instances. The test is as follows: var instance1 = new SubClass ("Chinese", "9:00"); instance1.getTime (); / / 9:00instance1.courses.push (Chemistry) instance1.getCourses () / ["Chinese", "Mathematics", "English", "Chemistry"] instance1.getCurrent (); / / Chinese console.log (instance1.current) / / Chinese var instance2 = new SubClass ("Mathematics", "10:00"); instance2.getTime (); / / 10:00instance2.getCourses (); / / [Chinese, Mathematical, English] instance2.getCurrent () / / Mathematical console.log (instance2.current) / / Mathematics but this pattern executes the parent class function once when executing the subclass constructor, and again when implementing the subclass prototype inheritance, and calls the parent class constructor twice, which is obviously a design flaw, is there a better way? In view of this defect, parasitic combinatorial inheritance appears. Before introducing this kind of inheritance, we need to understand "prototype inheritance" and "parasitic inheritance". To understand prototype inheritance function inheritObject (o) {function F () {} F.prototype = o; return new F ();} var course = {name: "Chinese", alikeCourse: ["Mathematics", "English"],} Var newCourse = inheritObject (course); newCourse.name = "chemistry"; newCourse.alikeCourse.push ("physics"); var otherCourse = inheritObject (course); otherCourse.name = "politics"; otherCourse.alikeCourse.push ("history"); console.log (newCourse.name); / / chemical console.log (newCourse.alikeCourse); / / [mathematics, English, physics, history] console.log (otherCourse.name); / / political console.log (otherCourse.alikeCourse) / / [Mathematics, English, Physics, History] console.log (course.name); / / Chinese console.log (course.alikeCourse); / / [Mathematics, English, Physics, History] inheritObject can be seen as an encapsulation of class inheritance, in which the excessive class F is equivalent to a subclass of class inheritance. The problem of sharing reference types in class inheritance still exists, but there is no content in the excessive class F constructor, so the overhead is less. Parasitic inheritance "parasitic inheritance" continues to be enhanced on the basis of "prototype inheritance". Function inheritObject (o) {function F () {} F.prototype = o; return new F ();} var course = {name: "Chinese", alikeCourse: ["Mathematics", "English"],}; function createCourse (obj) {/ / create a new object var o = new inheritObject (obj) by prototype inheritance; / / expand the new object o.getName = function () {console.log (this.name);}; return o } const newCourse = createCourse (course) this way continues to grow attributes within an object, like parasitic growth, so it is called parasitic inheritance. Parasitic inheritance is the secondary encapsulation of prototype inheritance, and the inherited object is extended in the process of secondary encapsulation, so that the newly created object not only has the properties and methods in the parent class, but also adds new properties and methods. On the basis of this idea, combined with combinatorial inheritance, the implementation of "parasitic combinatorial inheritance" function inheritObject (o) {function F () {} F.prototype = o; return new F () is derived. } function inheritPrototype (subClass, superClass) {/ / copy a prototype copy of the parent class in the variable var p = inheritObject (superClass.prototype) / / modify because rewriting the subclass prototype causes the constructor property of the subclass to be modified p.constructor = subClass / / set the prototype of the subclass subClass.prototype = p} save a copy and assign a value to the subclass prototype to achieve inheritance And the parent class function is not called again, and the test is as follows, which is similar to the combinatorial inheritance pattern / / testfunction SuperClass (current) {/ / reference type common attribute this.courses = ["Chinese", "Mathematics", "English"] / / the common attribute of the value type this.current = current;} SuperClass.prototype.getCourses = function () {console.log (this.courses);}; SuperClass.prototype.getCurrent = function () {console.log (this.current);}; / / declare that the subclass function SubClass (current, time) {/ / the constructor inherits the parent class attribute SuperClass.call (this, current); this.time = time } / / parasitic inheritance subclass prototype inherits parent class inheritPrototype (SubClass, SuperClass); / / classlike inheritance subclass prototype inherits parent class / / SubClass.prototype = new SuperClass (); / / subclass prototype method SubClass.prototype.getTime = function () {console.log (this.time);}; var instance1 = new SubClass ("Chinese", "9:00"); var instance2 = new SubClass ("Mathematics", "10:00"); instance1.getTime () / / 9:00instance1.courses.push (Chemistry); instance1.getCourses (); / [Chinese, Mathematics, English, Chemistry] instance1.getCurrent (); / / Chinese console.log (instance1.current); / / Chinese instance2.getTime (); / / 10:00instance2.getCourses (); / [Chinese, Mathematics, English] instance2.getCurrent () / / Mathematical console.log (instance2.current); / / Mathematical

The difference is only in

/ / parasitic inheritance subclass prototype inherits parent class inheritPrototype (SubClass, SuperClass); / / classlike inheritance subclass prototype inherits parent class / / SubClass.prototype = new SuperClass (); thus, multiple instances of multiple subclasses do not affect each other, and the parent class constructor is called only once, which is the ultimate mode of JavaScript inheritance. After reading this article, I believe you have some understanding of "sample Analysis of implementation inheritance in javascript". If you want to know more about it, you are welcome to follow the industry information channel. Thank you for reading!

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.

Share To

Development

Wechat

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

12
Report