skip to Main Content

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

2

Answers


  1. Just assign to the function:

    function Food () {
        
    }
    
    Food.isEdible = true;
    
    console.log(Food.isEdible); 
    Login or Signup to reply.
  2. 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

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search