js原生继承几种方式

js原生继承

js自己并无继承和类的概念,本质上是经过原型链(prototype)的形式实现的。app

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继承this

// 这样直接将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构造函数继承spa

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

综上,能够根据本身的实际需求去选择合适的继承方式。prototype

相关文章
相关标签/搜索