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?

5
  • 4
    "Static" properties are simply properties on the constructor function objects. They don't have anything to do with the JavaScript inheritance scheme. Commented Sep 25, 2019 at 14:48
  • 1
    Try console.dir(MyConstructor) to see the static properties. Commented Sep 25, 2019 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. Commented Sep 25, 2019 at 15:02
  • 3
    Possible duplicate of How to inherit static methods from base class in JavaScript? Commented Sep 25, 2019 at 15:25
  • "Or Object.create(...)" - it's not exactly optional Commented Sep 25, 2019 at 19:41

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.