how to define a static property in the ES6 classes [duplicate]
class Game{ constructor(){} } Game.cards = []; Game.cards.push(1); console.log(Game.cards); You can define a static variable like that.
class Game{ constructor(){} } Game.cards = []; Game.cards.push(1); console.log(Game.cards); You can define a static variable like that.
Immediately instantiated anonymous class — is it a bad idea? Yes, a very bad one. Just as bad as new function() { … } was in ES5. This writing style leads to the creation of a new constructor function and prototype object every time the expression is evaluated. If you create multiple objects with this … Read more
EDIT (2021): TC39, which specifies JavaScript still hasn’t resolved exactly how this is supposed to work. That needs to happen before browsers can consistently implement it. You can follow the latest efforts here. Original answer: Instantiating such classes is meant to work; Chrome and Firefox just have bugs. Here’s Chrome’s, here’s Firefox’s. It works fine … Read more
I was getting this error due to a circular dependency, like A injected with B B injected with C C injected with A Removing the circular dependecy fixed this error.
Can I do async constructor() No, that’s a syntax error – just like constructor* (). A constructor is a method that doesn’t return anything (no promise, no generator), it only initialises the instance. And, if not how should a constructor work that does this Such a constructor should not exist at all, see Is it … Read more
I would recommend neither. This is totally overcomplicated. If you only need one object, do not use the class syntax! Just go for import Constants from ‘../constants’; export default { url: Constants.API_URL, getCities() { return fetch(this.url, { method: ‘get’ }).then(response => response.json()); } }; import API from ‘./services/api-service’ or even simpler import Constants from ‘../constants’; … Read more
It is complicated; I tried a lot! In the end, this one-liner worked for my custom ES6 class instances: let clone = Object.assign(Object.create(Object.getPrototypeOf(orig)), orig) It avoids setting the prototype because they say it slows down the code a lot. It supports symbols but isn’t perfect for getters/setters and isn’t working with non-enumerable properties (see Object.assign() … Read more
Both ways are viable, but they do different things when it comes to inheritance with an overridden static method. Choose the one whose behavior you expect: class Super { static whoami() { return “Super”; } lognameA() { console.log(Super.whoami()); } lognameB() { console.log(this.constructor.whoami()); } } class Sub extends Super { static whoami() { return “Sub”; } … Read more