Creating an object with static members in ES6 JavaScript
I've been making a lot of objects in ES6 that have static functions. Until ES6 rolled around, there was no such distinction in the language. One thing that's hassled me lately is remember which class I instantiated an object from. I'm not entirely sure this is advisable but I've created a function that creates objects that includes the static members of a class.
const newWithStatic = (source, ...args) => {
let newObj = new source(...args);
Object.getOwnPropertyNames(source)
.filter(prop => typeof source[prop] === "function")
.forEach(prop => {
newObj[prop] = source[prop];
});
return newObj;
};
At the very least, it's a testament to the flexibility of JavaScript you are able to do something like this.
See if for yourself at JSFiddle.