我在当前项目中使用的设计模式是:
var MyConstructor = function() { ... };
MyConstructor.STATIC_PROPERTY = 'static';
现在,如果我想从MyConstructor类继承,我会做:
var ChildClass = function() { ... };
ChildClass.prototype = new MyConstructor(); // Or Object.create(...)
ChildClass.prototype.constructor = ChildClass;
问题是ChildClass.STATIC_PROPERTY
未定义/未继承...
是否有解决方法?
第二个问题:
如果我是console.log(MyConstructor)
,当它真正存在时,我会得到function() { ...}
,而关于MyConstructor.STATIC_PROPERTY
则一无所获。 STATIC_PROPERTY
到底存储在哪里?如何检查/显示它?
我会这样写,
function ExampleClass () { // constructor function
//You can do stuff like these below
var privateVar = "foo"; // Private
this.publicVar = "bar"; // Public
this.publicMethod = function () { //<- Public method
alert(privateVar);
};
}
// Static variable shared by all instances
ExampleClass.STATIC_PROPERTY = "baz";
var anInstance = new ExampleClass();
下面这些也可能有帮助
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes/static