Reputation: 80
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?
Upvotes: 3
Views: 2230
Reputation: 665536
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
.
Upvotes: 3