美文网首页
react中constructor()和super()

react中constructor()和super()

作者: ai_cuicui | 来源:发表于2020-03-01 19:06 被阅读0次

    constructor() ----- 构造方法
    这是es6对类的默认方法,通过new命令生成对象实例时自动调用该方法。并且该方法是类中必须有的,如果没有显示定义,则会默认添加一个空的constructor()方法。

    es6中,JavaScript没有继承的写法,需要通过prototype来达到目的。比如:

    function People (name, age) {
        this.name = name;
        this.age = age
    }
    People.prototype.sayName = function () {
        return '我的名字是' + this.name
    }
    
    //创建新的子类 p1
    let p1 = new People(‘hasana’, 18)
    

    在es6中,可以通过class来实现,比如:

    class People {
        //构造方法constructor就等于上面的构造函数People
        constructor (name, age) {
            this.name = name;
            this.age = age
        }
        sayName () { 
            return '我的名字是' + this.name
        }
    }
    
    //创建新的子类 p1
    let p1 = new People(‘hasana’, 18)
    

    以上得出结论,构造方法constructor()其实就是构造函数本身。

    super() ---- 继承

    在class方法中,继承是使用extends关键字来实现的,比如:

    class People {
        constructor (name, age) {
            this.name = name;
            this.age = age
        }
        sayName () {
            return '我的名字是' + this.age
        }
    }
    
    class Child extends People {
        constructor (name, age, sex) {
            super(name , age);
            this.sex = sex
        }
        haha () {
            return this.sex + ' ' + super.sayName();   //调用父类的sayName()
        }
    }
    
    

    上面的例子中,出现了super(),子类必须在constructor()调用super()方法,否则新建实例时就会报错。
    报错的原因是: 子类没有自己的this对象,他只能继承父类的this对象,然后对其进行加工,而super()就是将父类的this对象继承给子类,没有super,子类就得不到this对象。

    es5中new过程:

    在es5的继承中先创建子类的实例对象this,然后再将父类的方法添加到this上(Parent.apply(this) ).而es6采用的是先创建父类的实例this(先调用super()方法),然后再用子类的构造函数修改this。

    总结:
    1.子类如果没有constructor方法,该方法会被默认添加,任何的子类都有constructor方法,无论有没有定义,都存在。
    2.在子类的构造函数constructor中,只有调用super()方法之后,才可以使用this关键字,否则会报错。

    相关文章

      网友评论

          本文标题:react中constructor()和super()

          本文链接:https://www.haomeiwen.com/subject/aczlqhtx.html