In class
syntax, we can access the constructor easily:
class MyClass {
static get STATIC_PROP() {
return 500;
}
getStaticProp() {
return this.constructor.STATIC_PROP;
}
}
item = new MyClass();
console.log(item.getStaticProp()); // prints 500, so: cool!!
But in prototype
syntax, it does not seem that easy:
MyClass = function() {};
MyClass.STATIC_PROPERTY = 500;
MyClass.prototype = {
getStaticProp() {
return this.constructor.STATIC_PROPERTY
}
}
item2 = new MyClass();
console.log(item2.getStaticProp()); // prints undefined, so: not cool... it should print: 500
Can anyone help me to find out how can I achieve what I am doing in the first code, within the paradigm of the second code (meaning prototype
and not class
).
Thank you in advance.
EDIT: I could solved this by adding:
MyClass.prototype.constructor = MyClass;
I guess this is the only way to remain functional while accessing static properties from prototype
methods.