Skip to content

Instantly share code, notes, and snippets.

@jacobstr
Created December 19, 2014 21:58
Show Gist options
  • Select an option

  • Save jacobstr/fbca6104b5e83f22fe50 to your computer and use it in GitHub Desktop.

Select an option

Save jacobstr/fbca6104b5e83f22fe50 to your computer and use it in GitHub Desktop.
ES6 Static Factory Magic - How does it work?
class Parent {
static build() {
return new this();
}
}
class Child extends Parent {
}
assert(Child.build() instanceof Child);
@jacobstr
Copy link
Author

This pattern works in the browser for me via Reactify's transformer.
It fails during my tests where I'm using the 6to5 jest plugin.

It seems like this might be a bit of a grey area. I'm counting on the fact that this should be (in lieu of call / apply / bind) bound to "nearest" object to which the function is attached. In this case, that should be Child.

If you stick a console.log(this) inside of build(), the browser prints Child, jest prints {}. Parent.build() works in both cases, however.

@jacobstr
Copy link
Author

Well that was a derp - copying and pasting an earlier test led to me calling:

new Child.build();

Instead of

Child.build();

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment