Home > Web Front-end > JS Tutorial > Four ways of inheritance in javascript (code examples)

Four ways of inheritance in javascript (code examples)

不言
Release: 2019-04-03 09:22:42
forward
1828 people have browsed it

This article brings you the four methods (code examples) of JavaScript inheritance. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

1. Prototype chain inheritance

Core: Use the instance of the parent class as the prototype of the subclass

Disadvantages: New prototype method for the parent class/ Prototype attributes can be accessed by subclasses. Once the parent class changes, everything else changes

        function Person (name) {
            this.name = name;
        };

        Person.prototype.getName = function () {    //对原型进行扩展
            return this.name;
        };

        function Parent (age) {
            this.age = age;
        };

        Parent.prototype = new Person('老明');   //这一句是关键 //通过构造器函数创建出一个新对象,把老对象的东西都拿过来。

        Parent.prototype.getAge = function () {
            return this.age;
        };

//        Parent.prototype.getName = function () {   //可以重写从父类继承来的方法,会优先调用自己的。
//            console.log(222);
//        };

        var result = new Parent(22);
        console.log(result.getName());  //老明  //调用了从Person原型中继承来的方法(继承到了当前对象的原型中)  
        console.log(result.getAge());   //22   //调用了从Parent原型中扩展来的方法
Copy after login

2. Constructive inheritance

Basic idea
Borrow constructor The basic idea is to use call or apply to copy (borrow) the properties and methods specified by this in the parent class to the instance created by the subclass.
Because this object is bound at runtime based on the execution environment of the function. That is, globally, this is equal to window, and when a function is called as a method of an object, this is equal to that object. The
call, apply methods can change the object context of a function from the initial context to the new object specified by thisObj.

So, this borrowed constructor is, when new the object (when new is created, this points to the created instance), a new instance is created Object,
and execute the code inside Parent, and Parent uses call to call Person, that is to say, this points to a new instance,
so the this related properties and methods in Person will be assigned to the new instance, and Instead of assigning the value to Person,
so all instances have these this attributes and methods defined by the parent class.

Because the properties are bound to this, they are assigned to the corresponding instances when called, and the values ​​of each instance will not affect each other.

Core: Using the constructor of the parent class to enhance the instance of the subclass is equivalent to copying the instance attributes of the parent class to the subclass (no prototype is used)

Disadvantages: Methods are all in the constructor As defined in, only instance properties and methods of the parent class can be inherited, prototype properties/methods cannot be inherited, and function reuse cannot be achieved. Each subclass has a copy of the parent class instance function, which affects performance

      function Person (name) {
            this.name = name;
            this.friends = ['小李','小红'];
            this.getName = function () {
                return this.name;
            }
        };

//        Person.prototype.geSex = function () {    //对原型进行扩展的方法就无法复用了
//            console.log("男");
//        };

        function Parent = (age) {
            Person.call(this,'老明');  //这一句是核心关键
            //这样就会在新parent对象上执行Person构造函数中定义的所有对象初始化代码,
            // 结果parent的每个实例都会具有自己的friends属性的副本
            this.age = age;
        };

        var result = new Parent(23);
        console.log(result.name);    //老明
        console.log(result.friends);  //["小李", "小红"]
     console.log(result.getName());  //老明
     console.log(result.age);    //23
     console.log(result.getSex());  //这个会报错,调用不到父原型上面扩展的方法
Copy after login

3. Combined inheritance

Combined inheritance (all instances can have their own properties and can use the same method. Combined inheritance avoids the defects of the prototype chain and borrowed constructors, and combines the two The advantage of each is the most commonly used inheritance method)

Core: By calling the parent class constructor, inherit the properties of the parent class and retain the advantages of passing parameters, and then use the parent class instance as the prototype of the subclass to achieve Function reuse

Disadvantages: The parent class constructor is called twice and two instances are generated (the subclass instance blocks the one on the subclass prototype)

        function Person  (name) {
             this.name = name;
             this.friends = ['小李','小红'];
         };

         Person.prototype.getName = function () {
             return this.name;
         };

        function Parent (age) {
            Person.call(this,'老明');  //这一步很关键
            this.age = age;
        };

        Parent.prototype = new Person('老明');  //这一步也很关键
        var result = new Parent(24);
        console.log(result.name);    //老明
        result.friends.push("小智");  //
        console.log(result.friends);  //['小李','小红','小智']
        console.log(result.getName());  //老明
        console.log(result.age);    //24

        var result1 = new Parent(25);   //通过借用构造函数都有自己的属性,通过原型享用公共的方法
        console.log(result1.name);  //老明
        console.log(result1.friends);  //['小李','小红']
Copy after login

4. Parasitic combination inheritance

Core: Through parasitism, the instance attributes of the parent class are cut off, so that when the constructor of the parent class is called twice, the instance method will not be initialized twice/ Attributes avoid the shortcomings of combined inheritance

Disadvantages: It is perfect, but the implementation is more complicated

        function Person(name) {
            this.name = name;
            this.friends = ['小李','小红'];
        }

        Person.prototype.getName = function () {
            return this.name;
        };

        function Parent(age) {
            Person.call(this,"老明");
            this.age = age;
        }

        (function () {
            var Super = function () {};     // 创建一个没有实例方法的类
            Super.prototype = Person.prototype;
            Parent.prototype = new Super();     //将实例作为子类的原型
        })();

        var result = new Parent(23);
        console.log(result.name);
        console.log(result.friends);
        console.log(result.getName());
        console.log(result.age);
Copy after login

[Related recommendations: JavaScript video tutorial]

The above is the detailed content of Four ways of inheritance in javascript (code examples). For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:segmentfault.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template