I'm trying to use the new ES7 syntax to pass in properties to a class without using a constructor.
I know we can pass in this with a constructor:
class MyClass {
constructor(pacman) {
this.pacman = pacman;
}
}
...
const myInstance = new MyClass({food:'........'});
But how we do this with a "constructorless" syntax in ES7?
Failing code:
class MyClass {
static pacman; // undefined
pacman = this.pacman; // undefined
this.pacman = pacman; // Syntax error: unexpected token .
pacman = this.pacman.bind(this); // Cannot read property 'bind' of undefined
}
...
const myInstance = new MyClass({food:'........'});
But how we do this with a "constructorless" syntax in ES7?
There is no constructorless syntax in ES2016. If you refer to the still experimental class fields proposal: a class field is only good for things that get initialised with the same value for every instance, it cannot depend on anything passed to the constructor. That's what you need a constructor
for. Only there you can declare parameters and use them to refer to the constructor arguments.