下面有两个对象构造函数Newobj是父对象,我想用一些额外的参数创建完全相同的对象构造函数
问题是:我想使用rest参数,但rest参数只能发送最后一个参数,我还想要一些额外的参数,如home,但(child2.home)给我一个输出。应该是45。它将显示姓名为jersey,地址为45。
//first constructor
function Newobj(name, adress) {
this.name = name;
this.adress = adress;
this.fullA = function () {
return this.name + " " + this.adress;
};
}
//second constructor using apply method for inheritance
function Newobj1(home, ...args) {
Newobj.apply(this, args);
this.home = home;
}
const child23 = new Newobj("ana", "newport");
const child2 = new Newobj1("ana1", "jersey", "45");
console.log({ child23, child2 });
.as-console-wrapper { min-height: 100%!important; top: 0; }
function newobj(name, address) {
this.name = name;
this.address = address;
this.fullA = function () {
return this.name + " " + this.adress;
};
}
//second constructor using apply method for inheritance
function newobj1(...args) {
const home = args[2] || "";
newobj.apply(this, args);
this.home = home;
}
const child23 = new newobj("ana", "newport");
const child2 = new newobj1("ana1", "jersey", "45");
const child3 = new newobj1("ana1", "jersey");
console.log(child2);
console.log(child23);
console.log(child3);