我知道 JS 继承已经被彻底讨论过,我自己也有几本关于它的书,但我还没有找到适合我当前构造函数模式的书,而且我没有掌握背后的理论它。
这是我使用过的对象模式:
MYAPP.Animal = function() {
function Animal() {
this.position = {x: 0, y: 0};
};
Animal.prototype.getPosition = function() {
return this.position.x;
};
return Animal;
}();
MYAPP.Dog = function() {
function Dog(param) {
this.name = param.name;
this.position.x = param.x;
};
Dog.prototype.getName = function() {
return this.name;
};
return Dog;
}();
var snoopy = new MYAPP.Dog({
name:"snoopy",
x: 10
});
var slinky = new MYAPP.Dog({
name:"slinky",
x: 20
});
我以为我已经破解了它,但后来看起来好像两只狗共享同一个 Animal 实例,并且第一只狗的位置被第二只狗覆盖。
这种方法可以继承吗?提前致谢
编辑:寻找普通的 JS 解决方案
最佳答案
您首先需要以某种方式链接Dog
和Animal
。您可以使用 .call()
和 Object.create()
修改后的代码可能如下所示:
MYAPP.Animal = function() {
function Animal() {
this.position = {x: 0, y: 0};
};
Animal.prototype.getPosition = function() {
return this.position.x;
};
return Animal;
}();
MYAPP.Dog = function() {
function Dog(param) {
MYAPP.Animal.call(this);
this.name = param.name;
this.position.x = param.x;
};
Dog.prototype = Object.create(MYAPP.Animal.prototype,{
getName: {
value: function() {
return this.name;
},
enumerable: true,
configurable: true,
writable: true
}
});
Dog.prototype.constructor = Dog;
return Dog;
}();
var snoopy = new MYAPP.Dog({
name:"snoopy",
x: 10
});
var slinky = new MYAPP.Dog({
name:"slinky",
x: 20
});
关于javascript - 找不到有效的 JavaScript 继承模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28126289/