我有这样的东西:
dog = function () {
this.age;
this.name;
this.dog1 = new dog.shepherd();
}
dog.prototype = {
bark : function () {
alert( (this.getName()) + " is barking." );
},
[3]**getName** : function () {
return this.name;
}
}
dog.shepherd = function () {
this.something;
}
dog.shepherd.prototype = function () {
guard : function () {
alert( ([2]**parent.getName()**) + " is barking." );
}
}
window.onload = function () {
var n = new dog();
[1]**n.guard()**;
}
如何使用从 dog.speherd 原型(prototype)中原型(prototype)化为 dog 的函数?
换句话说,当[1]被执行时,然后[2]被写成伪代码,调用[3]。
我知道这段代码不应该工作;这只是为了帮助我解释我想要什么。
最佳答案
你的标题说你想使用组合,但你的问题正文暗示继承。以下是如何使用组合来执行此操作,这可能是更好的选择。牧羊人毕竟“不是”狗(反之亦然),因此这里可能不存在继承。
此外,您通常不想像现在这样设置函数的整个原型(prototype);只需添加您想要的功能。按照惯例,构造函数以大写字母开头。
function Shepherd(mydog) {
this.dog = mydog;
}
Shepherd.prototype.guard = function () {
alert( this.dog.getName() + " is barking." );
}
function Dog(age, name) {
this.age = age;
this.name = name;
}
Dog.prototype.getName = function () {
return this.name;
}
Dog.prototype.bark = function () {
alert(this.getName() + " is barking." );
}
window.onload = function () {
var someDog = new Dog(4, "Ubu");
var someShepherd = new Shepherd(someDog);
someShepherd.guard();
}
关于javascript - 如何使用 JavaScript 组合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8279946/