关于 JavaScript 中的继承
关于 JavaScript 中的继承
ES5 之前,继承是这样实现的
#include<stdio.h>
int main()
{
int arr[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
int i = 0;
int j = 0;
int k = 0;
int sz = sizeof(arr) / sizeof(arr[0]);
int arr2[10] = { 0 };
int arr3[10] = { 0 };
while (i < sz)
{
if (arr[i] % 2 == 1)
{
arr2[j] = arr[i];
j++;
i++;
}
else
{
arr3[k] = arr[i];
k++;
i++;
}
}
i = 0;
j --;
k --;
while (j != -1)
{
arr[i] = arr2[j];
j--;
i++;
}
while (k != -1)
{
arr[i] = arr3[k];
i++;
k--;
}
for (i = 0; i < sz; i++)
{
printf("%d ", arr[i]);
}
return 0;
}
这种方式有个缺点,需要首先实例化父类。这表示,子类需要知道父类该如何初始化。
理想情况下,子类不关心父类的初始化细节,它只需要一个带有父类原型的对象用来继承即可。
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
参考
- Implementing Inheritance in JavaScript
- proto VS. prototype in JavaScript
linuxboy的RSS地址:https://www.linuxboy.net/rssFeed.aspx
本文永久更新链接地址:https://www.linuxboy.net/Linux/2019-05/158410.htm
评论暂时关闭