2012-04-06 86 views
0

在javascript中,如果我需要對象,每個有屬性的個人價值,我可以把它在構造函數中,像這樣:共享屬性在Javascript

function A(x) { 
    this.a = x; 
} 

如果我想要一個某些屬性要在對象之間共享,我可以在構造函數的原型中設置它。

function B() {} 
B.prototype.b = 'B0'; 

但是在中間情況下該怎麼辦?基本上,我有一個現有的代碼,其中所有構造的對象都從原型繼承了一個屬性,但現在我需要將它們分成幾個組,以便組中的所有成員共享一個屬性。

有沒有辦法專門構造函數B以某種方式?

回答

1

B.prototype.b不會像您所設想的那樣創建靜態屬性。這是比這更復雜一些,附着於原型分享他們與其他實例值,屬性,直到它們將覆蓋該值,這意味着:

var Foo = function(){ 
}; 
Foo.prototype.bar = 'bar'; 

var f1 = new Foo(); 
console.log(f1.bar); //outputs 'bar' 
var f2 = new Foo(); 
console.log(f2.bar); //outputs 'bar' 

f2.bar = 'notbar'; 
console.log(f2.bar); //outputs 'notbar' 
console.log(f1.bar); //outputs 'bar' 

只有這樣,纔能有「真正的」靜態屬性是它們附加在構造函數本身:中Foo

Foo.bar2 = 'bar2'; 

實例都可以訪問該值與Foo.bar2

所以回答你的問題是爲每個組創建「子類」(即從基類的構造函數繼承其原型構造函數)和每個子類附加屬性,如:

var Base = function(){ 
}; 
Base.prototype.getSomething = function(){ 
    return this.constructor.something; 
}; 
Base.prototype.setSomething = function(value){ 
    this.constructor.something = value; 
} 
var Group1 = function(){ 
}; 
Group1.prototype = new Base(); //classical inheritance 
Group1.prototype.constructor = Group1; 
Group1.something = 'something'; 
var Group2 = function(){ 
}; 
Group2.prototype = new Base(); //classical inheritance 
Group2.prototype.constructor = Group2; 
Group2.something = 'something else'; 

var g1a = new Group1(); 
var g1b = new Group1(); 
var g2a = new Group2(); 
var g2b = new Group2(); 

g1a.setSomething('whatever'); 

console.log(g1a.getSomething()); //outputs 'whatever' 
console.log(g1b.getSomething()); //outputs 'whatever' 
console.log(g2a.getSomething()); //outputs 'something else' 
console.log(g2b.getSomething()); //outputs 'something else' 

警告:Group1.prototype = new Base();其實是不好的做法,我寫了一個博客帖子大約3類型的繼承短短數天前這解釋了爲什麼:

http://creynders.wordpress.com/2012/04/01/demiurge-3-types-of-javascript-inheritance-2/

+0

太好了!但是如果我的構造函數實際上有參數呢? – 2012-04-06 10:17:50

+0

你究竟是什麼意思? Group1和Group2是可以有參數的普通構造函數。如果他們需要調用超級構造函數,他們可以像這樣直接調用它:'Base.call(this)',或者你可以像我的博客帖子那樣執行'__super__'技巧。 – Creynders 2012-04-06 11:54:59