JavaScript 对象子类
我想创建从超类 A 继承的子类 B。 我的代码在这里:
function A(){
this.x = 1;
}
B.prototype = new A;
function B(){
A.call(this);
this.y = 2;
}
b = new B;
Console.log(b.x + " " + b.y );
运行时,它显示 B 未定义。
I want to create sub-class B that inherits from super-class A.
my code here:
function A(){
this.x = 1;
}
B.prototype = new A;
function B(){
A.call(this);
this.y = 2;
}
b = new B;
Console.log(b.x + " " + b.y );
when run it,it show B is undefined.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
在尝试访问 B 的原型之前,您必须定义 B 构造函数:
You must define the B constructor function before trying to access its prototype:
应该
should be
Lynda.com 建议您接下来将构造函数重新分配给 B,如下所示。
Lynda.com advises that you next reassign the constructor to B, as follows.
在标准类派生中,从新创建的基类实例(B.prototype = new A)派生几乎是普遍的错误。 基类构造函数至少会执行不必要的代码,最坏的情况可能是在没有输入参数的情况下崩溃,而输入参数不应仅仅为了派生而人为创建。 此外,基类实例的实例函数成为派生类原型的一部分,这纯粹是运气好。
让我们说清楚! 如果您从基类构造函数(B.prototype = new A)创建的基类实例继承,那么您实际上并不是直接从基类继承! 你已经在继承链中创建了一个中介,即基类实例!!! 哎哟!!!! 这是低效的,因为在继承链中寻找继承的属性值需要额外的深度。 每次你犯这个错误时,这个深度都会累积。
那么正确的做法是怎样的呢。 你应该写而不是 B.prototype = new A
B.prototype = Object.create(A.prototype). 这在09年可能还没有。但是在09年仍然有
作为Object.create的替代品。 你应该写而不是 B.prototype = new A
B.prototype = 09中的protoProxy(A);
In standard class derivation, there is the nearly universal mistake of deriving from a newly created base class instance (B.prototype = new A). The base class constructor at the very least executes unnecessary code and at the worst may crash without the input arguments that shouldn't have to be artificially created just for the sake of derivation. Furthermore, instance functions of the base class instance becomes part of the derived classes prototype, which is appropriate only by sheer luck.
Lets be clear! If you inherit from a base class instance created by the base class constructor (B.prototype = new A) you are not actually directly inheriting from the base class!! You have created an intermediary in the inheritance chain, namely the base class instance!!! Ouch!!!! This is inefficient because there is an extra depth in seeking inherited property values in the inheritance chain. This depth accumulates every time you make this mistake.
So what's the correct way. Instead of B.prototype = new A you should write
B.prototype = Object.create(A.prototype). This may not have been available in 09. However in 09 there still was
as a substitute for Object.create. Instead of B.prototype = new A you should write
B.prototype = protoProxy(A) in 09;