继承JavaScript的静态属性

问题描述 投票:2回答:1

我在当前项目中使用的设计模式是:

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到底存储在哪里?如何检查/显示它?

javascript class inheritance properties static
1个回答
0
投票

我会这样写,

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://web.archive.org/web/20120502014437/http://www.tipstrs.com/tip/1084/Static-variables-in-Javascript

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes/static

© www.soinside.com 2019 - 2024. All rights reserved.