JS六大继承(下)
原型式继承
利用一个空构造函数为中介,将某个对象直接赋值给构造函数的原型
//将传进来的对象进行浅复制,放入空构造函数F的原型上,最后返回
function createObj(obj) {
function F() { }
F.prototype = obj;
return new F();
}
let person = {
name: 'yu',
friends: ['li', 'chen']
}
let person1 = createObj(person);
//Object.create 与 createObj 作用一样
let person2 = Object.create(person);
person1.name = '我是1';
console.log(person2.name);
person1.friends.push('yuyu');
console.log(person2.friends);
console.log("person1==>", person1)
console.log("person2==>", person2)
缺点:很明显,当继承的包含引用类型数据时,多个实例的引用地址是一样的
寄生式继承
// 核心:在原型式继承的基础上,增强对象,返回构造函数
function createEle(obj) {
// 先是原型式继承
let clone = Object.create(obj);
clone.hello = function () { // 以某种方式来增强对象
console.log("hello");
};
return clone; // 返回这个对象
}
缺点跟原型式继承一样,寄生式继承只是在原型式继承上的一个增强
组合寄生式继承
function inheritPrototype(son, father) {
// 新建对象,将父类的原型浅复制到一个空对象中
let prototype = Object.create(father.prototype);
// 增强对象,纠正原型链
prototype.constructor = son;
// 指定对象,将新创建的对象赋值给子类的原型
son.prototype = prototype;
}
// 父类
function Father(name, age) {
this.name = name;
this.age = age;
this.sayHello = function () {
console.log("hello son")
}
}
Father.prototype.sex = 'man';
Father.prototype.sayHello2 = function () {
console.log("hello my son")
}
//构造函数式继承
function Son(name, age) {
Father.call(this, name, age)
}
//寄生式继承原型
inheritPrototype(Son, Father);
const son = new Son('小明', 18);
son.sex = 'women'
console.log("son==>", son);
组合寄生式继承解决了原本组合式继承的需要new 多次的问题,这是最成熟的方法,也是现在库实现的方法