gpt4 book ai didi

javascript - 两个实现属性相同但原型(prototype)不同的javascript对象

转载 作者:行者123 更新时间:2023-11-29 22:07:58 26 4
gpt4 key购买 nike

我正在尝试创建 2 个共享相同实现方式的对象:

function Human(hand,leg,head,body,foot1,foot2){

this.hand = hand;
this.leg = leg;
this.head = head;
this.body = body;
this.feet = [foot1,foot2];
}


function Robot(hand,leg,head,body,foot1,foot2){

this.hand = hand;
this.leg = leg;
this.head = head;
this.body = body;
this.feet = [foot1,foot2];
}

我希望他们有不同的原型(prototype):

Human.prototype.scream = function(){ 
alert("HUMANNN");
//some other functions
};

Robot.prototype.scream = function(){
console.log("ROBOOBOT");
//some other functions
};

var Tom = new Robot(1,2,3,4,5,6);
Tom.scream();

var I = new Human(312314123,2141123,213131412,4121312,132124,12313);
I.scream();

是否有更好的方法来创建函数 HumanRobot 以便我不必编写两次?

我试过了

function Robot(hand,leg,head,body,foot1,foot2){

Human(hand,leg,head,body,foot1,foot2);

}

var Micky = new Robot(1,2,3,4,5,6);
Micky.scream();

但是没有用。

最佳答案

I tried

function Robot(hand,leg,head,body,foot1,foot2){
Human(hand,leg,head,body,foot1,foot2);
}

这确实将 Human 作为函数调用,而不是作为构造函数 - 不是在实例上,而是将全局对象作为 this value .您需要使用 .call :

function Robot(hand,leg,head,body,foot1,foot2) {
Human.call(this, hand,leg,head,body,foot1,foot2);
}

或者,如果您不想将它们写出来,您可以使用 arguments objectapply :

function Robot() {
Human.apply(this, arguments);
}

但是,我建议不要从一个构造函数调用另一个构造函数,而是将通用代码放入一个通用构造函数中,然后从 HumanRobot 中调用它,这样您也可以将特定的实例初始化代码放入它们的构造函数中:

function Humanoid (hand, leg, head, body, foot1, foot2) {
this.hand = hand;
this.leg = leg;
this.head = head;
this.body = body;
this.feet = [foot1, foot2]
}
function Human() {
Humanoid.apply(this, arguments);

}
// if you want Humans to inherit Humanoid prototype properties:
// Human.prototype = Object.create(Humanoid.prototype);
Human.prototype.… = …;

function Robot() {
Humanoid.apply(this, arguments);

}
// if you want Robots to inherit Humanoid prototype properties:
// Robot.prototype = Object.create(Humanoid.prototype);
Robot.prototype.… = …;

A way to create the functions Human and Robot so that I don't have to write it twice?

如果您确定构造函数代码始终完全相同,您也可以使用闭包:

function getConstructor() {
return function Human(hand,leg,head,body,foot1,foot2) {
this.hand = hand;
this.leg = leg;
this.head = head;
this.body = body;
this.feet = [foot1,foot2];
}
}
var Human = getConstructor();
Human.prototype.… = …;
var Robot = getConstructor();
Robot.prototype.… = …;

关于javascript - 两个实现属性相同但原型(prototype)不同的javascript对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19831245/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com