js原生继承几种方式

js原生继承

js本身并没有继承和类的概念,本质上是通过原型链(prototype)的形式实现的。

1.先写两个构造函数Parent和Child,用于将Child继承Parent

function Parent() {
    this.animals = 'animals';
    this.show = function() {
        console.log(this.animals);
    }
}
Parent.prototype.pro = 'pro';
function Child() {
    this.dog = 'dog';
}

2.prototype继承

// 这样直接将Parent.prototype赋给Child.prototype的继承方式不可取,因为在改变Child.prototype里的属性会同时改变Parent.prototype
Child.prototype = Parent.prototype; // 不能访问构造函数属性,只能访问原型

// Object.create(Parent.prototype)构造的对象是一个空对象且它的原型指向Parent.prototype,所以这里的Parent.prototype是空对象,链接到了Parent.prototype,并不会影响到Parent.prototype
Child.prototype = Object.create(Parent.prototype); // 不能访问构造函数属性,只能访问原型

// 这种继承方式是将实例化后的Parent对象赋给Child的prototype,既可以访问Parent构造函数里边的属性,也可以访问原型属性
Child.prototype = new Parent();

// 以上任一操作完成后这一步必须操作,是将Child的构造函数指向自身,否则在执行完继承之后,实例化的对象构造函数是Parent
Child.prototype.constructor = Child;

3.call,apply构造函数继承

// 需要将Child改写如下,apply类似,但缺陷就是访问不到Parent.prototype的属性了
function Child() {
    Parent.call(this);
    this.dog = 'dog';
}

综上,可以根据自己的实际需求去选择合适的继承方式。

posted @ 2019-09-06 18:01  歆轶  阅读(1185)  评论(0编辑  收藏  举报