javascript继承,构造函数调用两次
结果是两个带有javascript继承,构造函数调用两次,javascript,inheritance,Javascript,Inheritance,结果是两个带有 未定义 假的 为什么警报会出现两次?我已经搜索过了,但还没有找到任何东西+不知道要搜索什么 结果应该是一个带有“false”的警报,还是我错了 太多了 创建父对象的新对象时会出现一个警报Child.prototype=new Parent
太多了 创建父对象的新对象时会出现一个警报
Child.prototype=new Parent当您创建子对象的新对象时,var childObject=new child(false,false,false)
创建父对象的新对象时,会出现一个警报Child.prototype=new Parent当您创建子对象的新对象时,var childObject=new child(false,false,false)
通过使用父级的构造函数为子级创建原型,将调用构造函数,这是您第一次警告未定义
为了创建一个仍然使用相同原型链但在创建原型时不调用父构造函数的原型,您需要在两者之间添加另一个步骤
function Parent (arg1, arg2) {
alert(arg1);
this.member1 = arg1;
this.member2 = arg2;
};
Parent.prototype.update = function () {
// parent method update
};
function Child (arg1, arg2, arg3) {
Parent.call(this, arg1, arg2);
this.member3 = arg3;
};
Child.prototype = new Parent;
Child.prototype.update = function () {
// overwritten method update
};
function init () {
var childObject = new Child(false, false, false);
childObject.update();
}
这将创建一个匿名函数(称为Base
),该函数将原型设置为父类的原型,然后将子类的原型分配给一个新的Base
,以保留继承,但在创建原型链时,不调用父级的构造函数。通过使用父级的构造函数为子级创建原型,将调用构造函数,这是未定义的子级的第一个警报
为了创建一个仍然使用相同原型链但在创建原型时不调用父构造函数的原型,您需要在两者之间添加另一个步骤
function Parent (arg1, arg2) {
alert(arg1);
this.member1 = arg1;
this.member2 = arg2;
};
Parent.prototype.update = function () {
// parent method update
};
function Child (arg1, arg2, arg3) {
Parent.call(this, arg1, arg2);
this.member3 = arg3;
};
Child.prototype = new Parent;
Child.prototype.update = function () {
// overwritten method update
};
function init () {
var childObject = new Child(false, false, false);
childObject.update();
}
这将创建一个匿名函数(称为Base
),该函数将原型设置为父类的原型,然后将子类的原型分配给一个新的Base
,以保留继承,但在创建原型链时不调用父级的构造函数。此处调用第一个警报:Child.prototype=new Parent代码>哦,伙计。谢谢!所以只要删除新的…不,你不能只删除new
关键字。请参见steveukx
answer了解正确方法。此处调用第一个警报:Child.prototype=new Parent代码>哦,伙计。谢谢!所以只要删除新的…不,你不能只删除new
关键字。有关正确的方法,请参见steveukx
答案。