0

I am using ES6 classes. I want to achieve this.

function Grid(color) {
  this.color = color;
};

Grid.prototype.indexes = [];

I want to set indexes as a property of protoype object. How to achieve this in ES6 classes?

class Grid {
    constructor(color) {
        this.color = color;
    };
}

Edit: Is there any other alternative than below mentioned solution?

class Grid {
    constructor(color) {
        this.color = color;
    };
}

Grid.prototype.indexes = [];

Disclaimer: I am completely new to javascript.

jefe23984
  • 69
  • 1
  • 7
  • add ```this.indexes = [];``` inside the constructor. – Sajeeb Ahamed Mar 23 '20 at 18:17
  • 1
    You can copy the last line from your first example and paste it after `class Grid {...}` [Javascript ES6 shared class variable](https://stackoverflow.com/questions/36922109/javascript-es6-shared-class-variable) – blex Mar 23 '20 at 18:18
  • @SajeebAhamed It would add indexes to the class, and not to the prototype right? – jefe23984 Mar 23 '20 at 18:18
  • 1
    @jefe23984 Sajeeb's approach would add indexes to each instance. And this is usually what you want to because having array in prototype potentially creates a lot of problems with shared mutable state. If you insist on sharing the array I'd recommend to put it in the class itself (using `static` keyword) so it won't look like an instance property. – Yury Tarabanko Mar 23 '20 at 18:26
  • If you are new to JavaScript, try to avoid attempting to mimic patterns that you are accustomed to from other languages. JavaScript is a rare breed. – Aluan Haddad Mar 23 '20 at 18:27
  • Thnx!! @YuryTarabanko – jefe23984 Mar 23 '20 at 18:28
  • Yeah. If you something like prototyping then extend the class and add new functionalities into the child class. – Sajeeb Ahamed Mar 23 '20 at 18:29
  • You need to do something like - class Grid { constructor(color) { this.color = color; }; indexes = [] } – Vishal Mar 23 '20 at 18:29
  • @Vishal Can you help me understand on how it will be shared among instances (i.e same copy or different) and can i access indexes outside the class? – jefe23984 Mar 23 '20 at 18:42
  • 1
    Yes you can use it outside the class using new operator. so someting like var greenGrid = new Grid('green') and then access greenGrid.indexes – Vishal Mar 23 '20 at 18:53

0 Answers0