I'm reading through the ES6 class information on Babel.js's documentation and noticed that it says that objects can now have dynamic property names:
var obj = {
...
// Computed (dynamic) property names
[ "prop_" + (() => 42)() ]: 42
};
This seems like it would be useful in classes as well. Is it possible to do something similar in an ES6 class without doing it in a constructor, i.e.:
class Foo {
[ "read" + (...)(['format1', 'format2']) ] {
// my format reading function
}
}
rather than doing something like this in the constructor:
class Foo {
constructor(opts) {
let formats = ['format1', 'format2'];
let self = this;
formats.forEach(function(format) {
self["read" + format] = function() {
// my format reading function
}
})
}
}
In other words, I want to be able to take some array, such as ['format1', 'format2']
and create two methods, readformat1
and readformat2
, in the class dynamically, without using the constructor. Is this possible?
The dynamic method is a procedure for the determination of the masses of asteroids. The procedure gets its name from its use of the Newtonian laws of the dynamics, or motion, of asteroids as they move around the Solar System.
In C# 4.0, a new type is introduced that is known as a dynamic type. It is used to avoid the compile-time type checking. The compiler does not check the type of the dynamic type variable at compile time, instead of this, the compiler gets the type at the run time.
Dynamic class loading enables classes to be loaded into the Java execution system at run-time. This allows new features and capabilities to be added to an application while it is running.
Yes, it's possible, you only missed the required ()
for the method signature:
class Foo {
[ "read" + ((format) => format)(myFormat) ]() {
// my format reading function // ^--- this what missed
}
}
Babel repl: long and ugly url here
As of your updated question: it's not possible (at least I'm not aware of it). So you can create methods with names resolved in runtime, but you cannot create N methods from the array using that syntax.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With