关于 JavaScript 中的继承
字数:264,预计阅读时间:1min
ES5 之前,继续是这样实现的 function Parent() {
this.foo = function() {
console.log('foo');
};
}
Parent.prototype.bar = function() {
console.log('bar');
}
function Child() {
}
Child.prototype = p = new Parent();
Child.prototype.constructor = Child;
var c = new Child();
c instanceof Parent; // true
c instanceof Child; // true
c.__proto__ === p; // true
c.__proto__.__proto__ === Parent.prototype; // true
c.__proto__.__proto__.__proto__ === Object.prototype; // true
c.__proto__.__proto__.__proto__.__proto__ === null; // true
c.foo(); // foo
c.bar(); // bar 这种方式有个缺点,需要首先实例化父类。这表示,子类需要知道父类该如何初始化。 理想情况下,子类不关心父类的初始化细节,它只需要一个带有父类原型的对象用来继承即可。 Child.prototype = anObjectWithParentPrototypeOnThePrototypeChain; 但是 js 中没有提供直接获取对象原型的能力,决定了我们不能像下面这样操作: Child.prototype = (function () {
var o = {};
o.__proto__ = Parent.prototype;
return o;
}()); 注意: instance.__proto__ === constructor.prototype // true 所以,改进的方式是使用一个中间对象。 // Parent defined as before.
function Child() {
Parent.call(this); // Not always required.
}
var TempCtor, tempO;
TempCtor = function() {};
TempCtor.prototype = Parent.prototype;
Child.prototype = tempO = new TempCtor();
Child.prototype.constructor = Child;
var c = new Child();
c instanceof Parent; // true - Parent.prototype is on the p.-chain
c instanceof Child; // true
c.__proto__ === tempO; // true
// ...and so on, as before 借助这个中间对象绕开了对父类的依赖。为了减少如上的重复轮子,ES5 中加入 // Parent defined as before.
function Child() {
Parent.call(this); // Not always required.
}
Child.prototype = o = Object.create(Parent.prototype);
Child.prototype.constructor = Child;
var c = new Child();
c instanceof Parent; // true - Parent.prototype is on the p.-chain
c instanceof Child; // true
c.__proto__ === o; // true
// ...and so on, as before 参考 |

【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· .NET周刊【3月第1期 2025-03-02】
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· [AI/GPT/综述] AI Agent的设计模式综述