javaScript 继承的个人理解

63 阅读1分钟

构造函数继承

// 利用构造函数进行继承,优点是可以实例的属性不会共享,可以穿参数。缺点是:每次调用都会初始化一遍创建实例
function Parent(name){
    this.name = name
}
// 不能继承原型上的属性
Parent.protoType.testProto = 1;
function Child(name){
    Parent.call(this, name)
}
const child1 = new Child('test');
console.log(child1.testProto) // undefined
const child2 = new Child('test1');

原型链继承

// 非得说优点的话就一个,实现了继承,缺点:实例会被共享,不能进行传递参数
function Parent(){
    this.name = 'test'
}
Parent.protoType.test = 'test1'
function Child(){}
Child.protoType = new Parent();

const child1 = new Child()
console.log(child1.test) // test1
console.log(child1.name) // undefined,访问不到也就是说这个name在构造函数的原型链上

组合式继承

// 组合式继承的优点:融合了原型链继承和构造函数继承,可以继承原型链和构造函数
// 缺点: 每次继承都会初始化两次父级实例
function Parent(name) {
    this.name = name;
}
Parent.protoType.test = '1';
function Child(name) {
    Parent.call(this,name);
    this.child = 'child'
}
Child.protoType = new Parent();
Child.protoType.constructor = Child;
const child1 = new Child('test');

原型式继承

const obj = {
    test: 'test'
}
const newObj = Object.create(obj, {
    test1: {
      value:"test1",        // 初始化赋值
      writable:true,       // 是否是可改写的
      configurable:true,   // 是否能够删除,是否能够被修改
      enumerable:true      //是否可以用for in 进行枚举
    },
})
console.log(newObj) // {test1: 'test1} test在这个对象的原型对象中
// Object.create底层实现,这和原型链基本一样,都会共享原型链上的属性
function createObj(o) {
    function F() {};
    F.protoType = o;
    return new F();
}

寄生式继承

// 借助一个新的变量去完成继承,缺点是:每次继承都会走一遍方法
function createObj(o) {
    const clone = Object.create(o);
    return clone;
}

组合寄生式继承

function Parent(name) {
    this.name = name;
}
function Child(name) {
    Parent.call(this,name);
}
function F(){}
F.protoType = Parent.protoType;
Child.protoType = new F()
const child1 = new Child('test')
// 这样继承的话就只调用一次new Parent