joken-前端工程师

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: :: :: 管理 ::
  404 随笔 :: 39 文章 :: 8 评论 :: 20万 阅读
// 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   joken1310  阅读(7)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 从HTTP原因短语缺失研究HTTP/2和HTTP/3的设计差异
· 三行代码完成国际化适配,妙~啊~
点击右上角即可分享
微信分享提示