// 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';
}
}
前端工程师、程序员
标签:
JavaScript
, vue3
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 从HTTP原因短语缺失研究HTTP/2和HTTP/3的设计差异
· 三行代码完成国际化适配,妙~啊~