3

The design pattern I use in my current project is:

var MyConstructor = function() { ... };
MyConstructor.STATIC_PROPERTY = 'static';

Now if i want to inherit from MyConstructor class, I'd do:

var ChildClass = function() { ... };
ChildClass.prototype = new MyConstructor(); // Or Object.create(...)
ChildClass.prototype.constructor = ChildClass;

Problem is ChildClass.STATIC_PROPERTY is undefined / not inherited ...

Is there a way to fix that?

Secondary question:

If I console.log(MyConstructor), I'd get function() { ...} and nothing about MyConstructor.STATIC_PROPERTY when it's actually there. Where is that STATIC_PROPERTY stored in the end? How can I check/display it?

FZs
  • 16,581
  • 13
  • 41
  • 50
sed lex
  • 70
  • 1
  • 9
  • 4
    "Static" properties are simply properties on the constructor function objects. They don't have anything to do with the JavaScript inheritance scheme. – Pointy Sep 25 '19 at 14:48
  • 1
    Try `console.dir(MyConstructor)` to see the static properties. – Pointy Sep 25 '19 at 14:49
  • Since you have access to `MyConstructor()` in the scope where you define `ChildClass`, something like `ChildClass.STATIC_PROPERTY = MyConstructor.STATIC_PROPERTY` should work. ( but might not be desirable ) As stated, it has nothing to do with prototypal inheritance. Nether is it static without using `Object.defineProperty()` or it's alternatives. We can overwrite it all we want. – Shilly Sep 25 '19 at 15:02
  • 3
    Possible duplicate of [How to inherit static methods from base class in JavaScript?](https://stackoverflow.com/questions/5441508/how-to-inherit-static-methods-from-base-class-in-javascript) – ponury-kostek Sep 25 '19 at 15:25
  • "*Or Object.create(...)*" - [it's not exactly optional](https://stackoverflow.com/questions/12592913/what-is-the-reason-to-use-the-new-keyword-here,) – Bergi Sep 25 '19 at 19:41

1 Answers1

2

Use an ES6 class, which does prototypically inherit from the parent class (constructor function object):

function MyConstructor() { /* … */ }
MyConstructor.STATIC_PROPERTY = 'static';

class ChildClass extends MyConstructor { /* … */ }
console.log(ChildClass.STATIC_PROPERTY);

The alternative would be to either copy all properties (like with Object.assign) or to use Object.setPrototypeOf on the ChildClass.

Bergi
  • 630,263
  • 148
  • 957
  • 1,375