美文网首页
JavaScript继承四部曲

JavaScript继承四部曲

作者: Nebulium | 来源:发表于2018-08-26 11:11 被阅读0次

    四部曲:创建父类、创建子类、添加关系、修正子类原型

    创建父类
    function Human(name, age) {
        this.name = name;
        this.age = age;
    }
    Human.prototype.sayName = function(){ console.log(this.name); };
    
    创建子类
    function Woman(name, age, height) {
        Human.apply(this, arguments); //维持实例属性
        this.height = height;
    }
    
    添加关系
    function F(){}
    F.prototype = Human.prototype;
    Woman.prototype = new F();
    // 相当于
    Woman.prototype = Object.create(Human.prototype);
    

    修正子类原型

    Woman.prototype.constructor = Woman;
    Woman.prototype.sayHeight = function(){ console.log(this.height); };
    

    相关文章

      网友评论

          本文标题:JavaScript继承四部曲

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