我正在尝试创建两个共享相同实现方式的对象:
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();
是否有更好的方法来创建函数 Human
和 Robot
,这样我就不必编写两次?
我试过了
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
object和 apply
:
function Robot() {
Human.apply(this, arguments);
}
但是,我建议不要从另一个构造函数中调用一个构造函数,而是将通用代码放入通用构造函数中,并从 Human
和 Robot
中调用它,这样您也可以将特定的实例初始化代码放入其构造函数中:
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 - 两个 JavaScript 对象具有相同的属性实现方式,但原型(prototype)不同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19831245/