关于 JavaScript 中的继承
栏目: JavaScript · 发布时间: 6年前
内容简介:ES5 之前,继续是这样实现的这种方式有个缺点,需要首先实例化父类。这表示,子类需要知道父类该如何初始化。理想情况下,子类不关心父类的初始化细节,它只需要一个带有父类原型的对象用来继承即可。
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;
}());
注意: __prototype__
不等于 prototype
,前者是通过 new
后者创建的,所以后者是存在于构造器上的,前者属性实例上的属性。方法及属性在原型链上进行查找时使用的便是 __prototype__
,因为实例才有 __prototype
。
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 中加入 Object.create
方法,作用与上面等效。
// 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
参考
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网
猜你喜欢:- 028.Python面向对象继承(单继承,多继承,super,菱形继承)
- PHP类继承、接口继承关系概述
- 面向对象:理解 Python 类的单继承与多继承
- java入门第二季--继承--java中的继承初始化顺序
- 前端基本功(七):javascript中的继承(原型、原型链、继承的实现方式)
- 组合还是继承,这是一个问题?——由模式谈面向对象的原则之多用组合、少用继承
本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。
Lua设计与实现
codedump / 人民邮电出版社 / 2017-8 / 49.00元
本书首先介绍了Lua中的数据结构,比如通用数据是如何表示的、Lua的字符串以及表类型的实现原理,接着讨论了Lua虚拟机的实现,并且将其中重点的一些指令进行了分类讲解,最后讨论了垃圾回收、模块实现、热更新、协程等的实现原理。一起来看看 《Lua设计与实现》 这本书的介绍吧!