0

I have been wrapping my head around pseudoclassical inheritance in Javascript , and continuing on this topic I wanted to set an Static property/method , for a defined Constructor function. I want to avoid the class syntax for it.

function Food () {
    isEdible = true;
}

console.log(Food.isEdible); // undefined

I know this example is wrong

I am wondering how it has been done on the rest of the Javascript Object model, with methods so important like for instance

Array.of(element1, element2, /* …, */ elementN)

Which can be accessed without the need of Instanciating an Array

1
  • The OP should have a look into either Reflect.defineProperty or Object.defineProperty, but also into either Reflect.getOwnPropertyDescriptor or Object.getOwnPropertyDescriptor...and regarding the OP's use case, the next one is an appropriate way...Reflect.defineProperty(Food, 'isEdible', { /* enumerable: false, */configurable: true, writable: true, value: true }); Commented May 8, 2024 at 13:38

2 Answers 2

1

Just assign to the function:

function Food () {
    
}

Food.isEdible = true;

console.log(Food.isEdible); 

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

Comments

-1

Array.of is a static method. The docs:

The Array.of() static method creates a new Array instance from a variable number of arguments, regardless of number or type of the arguments.

In class based inheritance, the way to write it would be:

class Array {
  static alert(element) {
    alert(element);
  }
}

Array.alert('test');

The equivalent of above in prototype inheritance is:

Array.alert = function(element) {
  alert(element);
};

Array.alert('test');

Playground to view the conversion in ES5

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.