作者B9 (叶酸酸)
看板Ajax
标题[ js ] 一个跟 inheritance 有关的心得
时间Mon Dec 19 23:51:01 2011
有一些书在讲 inheritance 的时候会叫你这样写:
function A(a)
{
this.a = a;
}
function B(b)
{
this.super_.apply(this, arguments);
}
B.prototype = new A;
B.prototype.super_ = A;
然後 b1 = new B(1); b2 = new B(2); 会变成 b1.a === 1 && b2.a === 2
这种利用 parent constructor initiate 的方法不适用三层以上的继承关系。
因为在 new 第三层的时候会丢出 RangeError: Maximum call stack size exceeded。
> -------------------------------------------------------------------------- <
function A(a)
{
this.a = a;
}
function B(b)
{
this.super_.apply(this, arguments);
}
B.prototype = new A;
B.prototype.super_ = A;
function C(c)
{
this.super_.apply(this, arguments);
}
C.prototype = new B;
C.prototype.super_ = B;
首先假设以上情境,然後 new C。
new C 的时候会进到 function C 的 context,在这个 context 里面,
this 已经是 instanceof C,所以 this.super_ 会 lookup C.prototype 的 super_,
也就是 this.super_ = B,到这里都符合我们的预期。
this.super_.apply(this, arguments) 等同於 B.apply(this. argumets)。
B.apply(this. arguments),的时候会进到 function B 的 context,
在这个 context 里面的 this 是 instanceof B 吗?不,其实是 instanceof C。
因为我们用了 apply 把原本 instanceof C 的 this 带进 function B 的 context。
然後在 function B 的 context 执行 this.super_.apply(this, arguments)。
刚刚说过在这个 context 的 this 是 instanceof C,而 instanceof C 的 super_
则要 lookup C.prototype.super_ 也就是 B。所以这时候,
在 function B context 的 this.super_.apply(this, arguments) 等於
B.apply(this, arguments),回到上一段的开头,变成一个无穷回圈……
--
Oni devas ami animalojn. Ili estas tiel bongustaj.
One should love animals. They are so tasty.
每个人都应该爱动物,他们是如此美味。
--
※ 发信站: 批踢踢实业坊(ptt.cc)
◆ From: 175.180.52.96
※ 编辑: B9 来自: 175.180.52.96 (12/20 00:39)
1F:推 sk1765:你这个只要第三层继承的人 不写C.prototype.super_ = B; 12/21 16:16
3F:→ sk1765:还是我理解错了 12/21 16:21
4F:→ B9: 当然可以,可是 super 的用途本来就是用来 refer super class 12/21 19:59
5F:→ B9: 只有第三层不写的话,不然乾脆都不要写 12/21 19:59