JavaScript:ECMAScript 5中的继承
我是JS的新手,很抱歉提出这个问题。我想从JavaScript:ECMAScript 5中的继承,javascript,oop,inheritance,Javascript,Oop,Inheritance,我是JS的新手,很抱歉提出这个问题。我想从A继承B。我做错了什么 只有在创建B的实例之后,才调用inherit() 在定义两个函数之后,您需要静态地调用inherit() 您还需要在B中对实例调用A 有关如何正确执行继承的详细信息,请参阅。您仅在创建B的实例后调用inherit() 在定义两个函数之后,您需要静态地调用inherit() 您还需要在B中对实例调用A 有关如何正确执行继承的更多详细信息,请参阅 我做错了什么 两件事: 您正在调用inherit内部B。你应该在外面做 在B内部,您应该
A
继承B
。我做错了什么 只有在创建B
的实例之后,才调用inherit()
在定义两个函数之后,您需要静态地调用inherit()
您还需要在B
中对实例调用A
有关如何正确执行继承的详细信息,请参阅。您仅在创建
B
的实例后调用inherit()
在定义两个函数之后,您需要静态地调用inherit()
您还需要在B
中对实例调用A
有关如何正确执行继承的更多详细信息,请参阅
我做错了什么
两件事:
inherit
内部B
。你应该在外面做B
内部,您应该调用A
,例如
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
或
通过自动参数
伪数组传递运行时收到的所有参数B
var A=函数(){
这是1.p1=2;
};
A.prototype.f1=函数(){
返回7;
};
var B=函数(){
叫(这个);//
我做错了什么
两件事:
您正在调用inherit
内部B
。您应该在外部执行此操作
在B
内部,您应该调用A
,例如
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
或
通过自动参数
伪数组传递运行时收到的所有参数B
像这样:
var A=函数(){
这是1.p1=2;
};
A.prototype.f1=函数(){
返回7;
};
var B=函数(){
调用(this);//您没有调用基构造函数。而且,如果只继承一次类就足够了
var A=函数(){
这是1.p1=2;
};
A.prototype.f1=函数(){
返回7;
};
var B=函数(){
A.应用(这个,论点);
};
继承(A、B);
函数继承(子函数、父函数){
Child.prototype=Object.create(Parent.prototype);
Child.prototype.constructor=Child;
}
var b=新的b();
console.log(b.p1);//此处未定义
您没有调用基构造函数。另外,如果只继承一次类就足够了
var A=函数(){
这是1.p1=2;
};
A.prototype.f1=函数(){
返回7;
};
var B=函数(){
A.应用(这个,论点);
};
继承(A、B);
函数继承(子函数、父函数){
Child.prototype=Object.create(Parent.prototype);
Child.prototype.constructor=Child;
}
var b=新的b();
console.log(b.p1);//此处未定义
“您还需要在b中的实例上调用A。”也许可以演示如何做到这一点,因为这并不琐碎(嗯,做起来很琐碎,但知道如何做却不琐碎)。(我肯定链接涵盖了它,但是…“您还需要在b中的实例上调用A。”也许可以演示如何做到这一点,因为它并不琐碎(嗯,做起来很琐碎,但知道怎么做却不琐碎)。(我肯定链接涵盖了它,但是…)谢谢你的回答!T.J.克劳德,你能简单地解释一下调用A.call(this);
@Rudziankoŭ:当你调用A.call(x,y,z)时会发生什么吗
,它调用函数A
,使A
的代码在A
的过程中成为x
,然后将y
和z
作为参数传递。它基本上做foo.bar(y,z)
所做的事情(在bar
内部成为be
foo
),但不必涉及对象属性表达式。(A.apply
与A.call
完全相同,只是如果要传递参数,可以将其作为类似于数组的对象,而不是像调用那样的单个参数)谢谢你的回答!T.J.Crowder,你能用几句话解释一下调用A.call(this);
@Rudziankoŭ:当你调用A.call(x,y,z)时会发生什么吗
,它调用函数A
,使A
的代码在A
的过程中成为x
,然后将y
和z
作为参数传递。它基本上做foo.bar(y,z)
所做的事情(在bar
内部成为be
foo
),但不必涉及对象属性表达式。(A.apply
与A.call
完全相同,只是如果要传递参数,可以将其作为类似于数组的对象,而不是像调用那样的单个参数)
A.apply(this, arguments);