[英]JavaScript: Inheritance in ECMAScript5
var A = function () {
this.p1 = 2;
};
A.prototype.f1 = function () {
return 7;
};
var B = function () {
inherit(A, B);
};
function inherit(Child, Parent) {
Child.prototype = Object.create(Parent.prototype);
Child.prototype.constructor = Child;
}
var b = new B();
console.log(b.p1); // get undefined here
I am new to JS, sorry for dump question. 我是JS新手,对转储问题感到抱歉。 I would like to inherit
B
from A
. 我想从
A
继承B
What am I doing wrong? 我究竟做错了什么?
You're only calling inherit()
after creating the instance of B
. 您仅在创建
B
实例之后才调用inherit()
。
You need to call inherit()
statically, once, after defining both functions. 在定义两个函数之后,您需要一次静态调用
inherit()
。
You also need to call A
on your instance in B
. 您还需要在实例
B
调用A
For more details on how to properly do inheritance, see my blog . 有关如何正确进行继承的更多详细信息,请参阅我的博客 。
What am I doing wrong?
我究竟做错了什么?
Two things: 两件事情:
You're calling inherit
inside B
. 您正在
B
内部调用inherit
。 You should be doing it outside. 你应该在外面做。
Inside B
, you should be calling A
, eg 在
B
内部,您应该调用A
,例如
A.call(this/*, other, args, here, if, needed*/);
or 要么
A.apply(this, arguments);
to pass on all of the arguments B
received at runtime via the automatic arguments
pseudo-array. 通过自动
arguments
伪数组传递在运行时接收的所有参数B
Like so: 像这样:
var A = function () { this.p1 = 2; }; A.prototype.f1 = function () { return 7; }; var B = function () { A.call(this); // <==== Added }; inherit(A, B); // <==== Moved function inherit(Child, Parent) { Child.prototype = Object.create(Parent.prototype); Child.prototype.constructor = Child; } var b = new B(); console.log(b.p1); // get 2 here now
You didn't call the base constructor. 您没有调用基本构造函数。 Also, it's enough if you inherit only once the classes.
另外,仅继承一次类就足够了。
var A = function () { this.p1 = 2; }; A.prototype.f1 = function () { return 7; }; var B = function () { A.apply(this, arguments); }; inherit(A, B); function inherit(Child, Parent) { Child.prototype = Object.create(Parent.prototype); Child.prototype.constructor = Child; } var b = new B(); console.log(b.p1); // get undefined here
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.