wsqww / devNote

开发笔记
3 stars 3 forks source link

js的六种继承,使用继承实现class extend #7

Open chanchunlei opened 3 years ago

chst365 commented 3 years ago
/*
    原型链继承
    缺点:1. 引用类型的属性被所有实例共享
         2. 在创建 Child 的实例时,不能向 Parent 传参
*/

function Parent() {
    this.name = '张三';
    this.names = ['zhangsan', 'lisi'];
}
Parent.prototype.getName = function () {
    console.log(this.name);
}
function Child() { }
Child.prototype = new Parent();
var child1 = new Child();
console.log(child1.getName());
child1.names.push('wangwu');
console.log('child1', child1.names);
var child2 = new Child();
console.log('child2', child2.names);
/*
    借用构造函数(经典继承)
    缺点:1. 方法都在构造函数中定义,每次创建实例都会创建一遍方法
*/
function Parent(name) {
    this.name = name;
    this.names = ['kevin', 'daisy'];
}
function Child(name) {
    Parent.call(this, name);
}
var child1 = new Child('zhangsan');
console.log(child1.name);
var child2 = new Child('lisi');
console.log(child2.name);
/*
    组合继承
    原型链继承和构造函数继承的合并
*/
function Parent(name) {
    this.name = name;
    this.colors = ['blue', 'green']
}
Parent.prototype.getName = function () {
    console.log(this.name);
}
function Child(name, age) {
    Parent.call(this, name);
    this.age = age;
}
Child.prototype = new Parent();
Child.prototype.constructor = Child;
var child1 = new Child('zhangsan', 18);
var child2 = new Child('lisi', 19);
child1.colors.push('black');
child2.colors.push('red');
console.log(child1.colors);
console.log(child2.colors);
/*
    原型式继承
    ES5 Object.create 的模拟实训,将传入的对象作为创建对象的原型
    缺点:包含引用类型的属性值始终都会共享相应的值
*/
function createObj(o) {
    function F() { }
    F.prototype = o;
    return new F();
}
var person = {
    name: 'zhangsan',
    friends: ['wangwu', 'lisi']
}
var person1 = createObj(person);
var person2 = createObj(person);
person1.name = 'zhaoyun';
console.log(person1.name, person1);
console.log(person2.name, person2);
person1.friends.push('zhangfei');
console.log(person1.friends, person1);
console.log(person2.friends, person2);
/*
    寄生式继承:
    创建一个仅用于封装继承过程的函数,该函数在内部以某种形式来做增强对象,最后返回对象
    缺点:和借用构造函数一样,每次创建对象都会创建一遍方法
*/
function createObj(o) {
    var clone = Object.create(o);
    clone.sayName = function () {
        console.log('hi');
    }
    return clone;
}
/*
    寄生组合式继承
    优点:避免调用两次父构造函数
*/
function object(o) {
    function F() { }
    F.prototype = o;
    return new F();
}
function prototype(child, parent) {
    var prototype = object(parent.prototype);
    prototype.constructor = child;
    child.prototype = prototype;
}