joken-前端工程师

  :: 首页 :: 博问 :: 闪存 :: 新随笔 :: :: :: 管理 ::
// 1. 原型链继承
function Animal(name) {
    this.name = name;
    this.colors = ['black', 'white'];
}
Animal.prototype.getName = function () {
    return this.name;
};

function Dog(name) {
    this.type = 'dog';
}
Dog.prototype = new Animal();

// 2. 构造函数继承
function Bird(name) {
    this.name = name;
    Animal.call(this, name); // 继承属性
}

// 3. 组合继承(原型链 + 构造函数)
function Cat(name) {
    Animal.call(this, name); // 继承属性
    this.type = 'cat';
}
Cat.prototype = new Animal(); // 继承方法
Cat.prototype.constructor = Cat;

// 4. 原型式继承
const parent = {
    name: 'parent',
    getName: function () {
        return this.name;
    }
};
const child = Object.create(parent);

// 5. 寄生式继承
function createAnother(original) {
    const clone = Object.create(original);
    clone.sayHi = function () {
        console.log('hi');
    };
    return clone;
}

// 6. 寄生组合式继承(最理想的继承方式)
function inheritPrototype(subType, superType) {
    const prototype = Object.create(superType.prototype);
    prototype.constructor = subType;
    subType.prototype = prototype;
}

function Fish(name) {
    Animal.call(this, name);
    this.type = 'fish';
}
inheritPrototype(Fish, Animal);

// 7. ES6 的 class 继承
class Mammal {
    constructor(name) {
        this.name = name;
    }
    getName() {
        return this.name;
    }
}

class Rabbit extends Mammal {
    constructor(name) {
        super(name);
        this.type = 'rabbit';
    }
}

posted on 2024-12-02 21:26  joken1310  阅读(6)  评论(0编辑  收藏  举报