Let's just write a js inheritance

Inheritance is common in front-end logical operations. Today, we will write a js inheritance method from scratch

In es5, inheritance is essentially to create an instance object of a subclass first, and then add the method of the parent class to Parent.call(this). In es6, it is to create the instance object of the parent class, this, to call the super() of the parent class, and then modify this with the constructor of the subclass. The operation involved in any method is

 

1, Replace the call method of the current execution object with another object

Function.prototype.myCall = function() {
          let  obj = Array.from(arguments)[0] || window,
                arg = Array.from(arguments).slice(1),
                key = Symbol(),
            result
        obj[key] = this
        result = obj[key](...arg)
        delete obj[key]
        return result
    }

 

2, new method of creating instance object

function myNew(fn, arg) {
        let obj = {},
            fn = Array.from(arguments)[0],
            arg = Array.from(arguments).slice(1)
Object.setPrototypeOf(obj, fn.prototype) fn.myCall(obj,...arg) return obj }

 

After completing these two prerequisites, we start to use our own methods to complete js inheritance

function Fa(name) {
        this.name = name
    }
Fa.prototype.set1 = function() {
        return [...this.name]
    }

function Sa(name, age) {
        Fa.myCall(this,name)
        this.name = name;
        this.age = age
    }
Sa.prototype.set2 = function() {
        return [...this.age]
    }
Sa.prototype = myNew(Fa)

Sa.prototype.constructor = Sa

var qq = myNew(Sa, 123, 456)             
qq.set1()         //  [1,2,3]

Because the inheritance method of class in es6 must be called with the new keyword, all of which are not described here too much. The code is as follows

class Fa {
    constructor(name) {
        this.name = name
            }
    set() {
        return [...this.name]
                    }
        }
class Sa extends Fa {
    constructor(name, age) {
        super(name)
        this.age = age
                }
    }
var dd = new Sa(123, 456)

dd.set()                //[1,2,3]            

Keywords: Javascript

Added by Chotor on Sat, 01 Feb 2020 16:20:51 +0200