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/
太好了!但是如果我的構造函數實際上有參數呢? – 2012-04-06 10:17:50
你究竟是什麼意思? Group1和Group2是可以有參數的普通構造函數。如果他們需要調用超級構造函數,他們可以像這樣直接調用它:'Base.call(this)',或者你可以像我的博客帖子那樣執行'__super__'技巧。 – Creynders 2012-04-06 11:54:59