我正在用JavaScript做一些OOP的体验。我的目标是拥有一个父对象,它包含其他几个对象所共有的方法,这些方法是从父对象继承过来的。问题是,我希望父对象的方法能够读取子对象的字段。
我使用以下函数进行继承:
Function.prototype.inherits=function(obj){this.prototype=new obj();}以下是一些示例对象:
function Genetic(c){
this.code=c;
}
//My 'parent object':
function Animal(){
this.getCode=function(){
return(genetic.code);
}
}
g=new Genetic('test');
function Dog(){
genetic=g;
}
Dog.inherits(Animal);
g=new Genetic('foo');
function Cat(){
genetic=g;
}
Cat.inherits(Animal);
d=new Dog();
c=new Cat();现在,我希望d.getCode()返回'test',c.getCode()返回'foo'。问题是,两者都返回'foo'。变量genetic在Animal作用域中,而不在Dog/Cat作用域中。这意味着每当我创建一个继承自Animal的新对象时,genetic变量都会被覆盖。证明:
function Bla(){}
Bla.inherits(Animal);
bla=new Bla()
bla.getCode() //Returns 'foo'我可以使用var将genetic变量设置为Dog和Cat的私有变量:
function Dog(){
var genetic=g;
}问题是,因为genetic现在是Dog私有的,所以Animal对象不能访问它,这使得整个继承变得毫无意义。
你有什么办法解决这个问题吗?
编辑:另外,我希望gentic是私有的,这样就不能在Dog/Cat实例中修改它。
发布于 2011-09-09 02:15:09
变量'genetic‘在动物作用域中,而不在狗/猫作用域中。
不,genetic是全局。在整个应用程序中只有一个genetic变量。使其成为对象的属性。
此外,更好的继承方式如下所示:
function inherits(Child, Parent) {
var Tmp = function(){};
TMP.prototype = Parent.prototype;
Child.prototype = new Tmp();
Child.prototype.constructor = Child;
}然后,您可以让父构造函数接受参数,而不必重复代码:
//My 'parent object':
function Animal(g){
this.genetic = g;
}
Animal.prototype.getCode = function() {
return this.genetic.code;
}
function Dog(){
Animal.apply(this, arguments);
}
inherits(Dog, Animal);
function Cat(){
Animal.apply(this, arguments);
}
inherits(Cat, Animal);
var d = new Dog(new Genetic('test'));
var c = new Cat(new Genetic('foo'));我建议document your code properly遵循清晰的原型/继承链,而不是尝试做一些语言设计不适合的事情。
但是,使用上面给出的inherits函数,您可以执行以下操作:
function Animal(g){
var genetic = g
this.getCode = function(){
return genetic.code ;
}
}而其余的代码保持不变。然后你就有了你的“私有”变量,代价是每个实例都有自己的getCode函数。
编辑:这将不允许您在分配给Dog或Cat的任何函数中访问genetic,除非您还在它们的构造函数中保留了对该值的引用。
https://stackoverflow.com/questions/7352579
复制相似问题