2011-09-08 81 views
0

我正在做一些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' 

我可以genetic變量設置爲是的Dog和私有變量Cat使用var:

function Dog(){ 
    var genetic=g; 
} 

問題是,因爲genetic現在是私有的Dog,它不能是由Animal對象訪問,使整個繼承毫無意義。

您是否看到任何解決方法?

編輯:另外,我想gentic是私人的,所以它不能被修改在Dog/Cat實例。

回答

3

變量'genetic'位於Animal範圍內,而不在Dog/Cat範圍內。

沒有,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函數。

編輯:這不會讓你在分配給DogCat,除非您也保持在它們的構造函數值的引用的任何函數訪問genetic

+0

你是對的,但我希望變量是私人的,所以創建後不能修改!用你寫的代碼,我可以這樣做:d.genetic.code ='whadup bro'; – Alex

+0

@Alex:請參閱我的更新。 –

+0

好的,謝謝,所以我試圖做的事情是不可能的......你能解釋一下你給我的'inherit'函數的區別嗎? – Alex

相關問題