JS继承

一. 原型链继承

function parent() {
    this.name = "parent";
    this.toString1 = function() {
        console.log(this.name);
    }
    this.toString2 = () => {
        console.log(this.name);
    }
}

function child() {
    this.name = "child";
};

child.prototype = new Parent();
let obj = new child();

obj.toString1()    //parent 箭头函数绑定了this作用域
obj.toString2()    //child
  • 优点:instanceof 实例既是父类的实例,又是子类的实例
  • 缺点:无法实现多重继承

二. 构造函数继承

function parent() {
    this.name = "parent";
    this.toString1 = function() {
        console.log(this.name);
    }
    this.toString2 = () => {
        console.log(this.name);
    }
}

function child() {
    parent.call(this);
    this.name = "child";
};
  • 可以实现多重继承,把子类特有的属性设置放在构造器的内部
  • 使用instanceof发现,对象不是父类的实例
posted @ 2018-03-27 09:51  nina阿瑶  阅读(73)  评论(0编辑  收藏  举报