Now that JavaScript has classes thought I would offer an updated solution.
ES6 introduced an API that makes this extremely trivial but supports all new things JavaScript (modules for example, which weren't addressed in other answers, and doesn't worry about 'window' scope as mentioned in other comments). The Reflect API is well supported across browsers and all the methods are static and aren't limited to just classes, it works with objects in general.
The Reflect API even has convenience methods that are helpful beyond 'reflection-like' implementation. For example, you can quickly determine if an object has a key with:
console.log(Reflect.has(target, <key>))
Which can be considered an alternate of:
console.log(obj[<key>] !== undefined)
To instantiate a new instance of a class via javascript reflection you can call the Reflect.construct(<target>, arugmentsList)
method:
animal.js
export default class Animal {
constructor(type) {
this.type = type;
}
get canSwim() {
return ['amphibians', 'fish'].includes(this.type);
}
}
main.js
import Animal from "./animal.js"
const instance = Reflect.construct(Animal, ['bird']);
console.log(Reflect.get(instance, 'canSwim')) //returns false
Just for brevity, you can still use mutators and accessors per normal, I simply used the Reflection.get()
method for this example to demonstrate it exists, but the following is synonymous:
const instance = Reflect.construct(Animal, ['bird']);
console.log(instance.canSwim) //returns false
Of course, this works without modules, this example just demonstrates it with modules.
Reference: