1

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.

1 Answers1

1

Instead of assigning a new object to MyClass.prototype, you should define a new property on the MyClass.prototype object.

change

MyClass.prototype = {
  getStaticProp() {
    return this.constructor.STATIC_PROPERTY
  }
}

to

MyClass.prototype.getStaticProp = function() {
   return this.constructor.STATIC_PROPERTY
}

const MyClass = function() {};
MyClass.STATIC_PROPERTY = 500;

MyClass.prototype.getStaticProp = function() {
   return this.constructor.STATIC_PROPERTY
}

const item2 = new MyClass();
console.log(item2.getStaticProp());

You could use the name of the constructor function directly to access the static property

const MyClass = function() {};
MyClass.STATIC_PROPERTY = 500;

console.log(MyClass.STATIC_PROPERTY);
Yousaf
  • 27,861
  • 6
  • 44
  • 69