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.bar2 = 'bar2';
的实例Foo
必须使用 访问该值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/