Skip to content

Instantly share code, notes, and snippets.

@luislobo
Created October 17, 2017 16:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save luislobo/4451e141655d7ba55548cbdc29e577d0 to your computer and use it in GitHub Desktop.
Save luislobo/4451e141655d7ba55548cbdc29e577d0 to your computer and use it in GitHub Desktop.
How to create ES6 static methods that create objects of itself
class A {
constructor(name){
this.name = name;
}
static create(name){
return new this(name);
}
static create2(name){
return new A(name);
}
toString() {
return this.name;
}
}
class B extends A {
constructor(name){
super(name);
this.name = 'B:' + this.name;
}
}
let a1 = A.create('luis');
let a2 = new A('luis');
let a3 = A.create2('luis');
console.log(a1.toString(), a2.toString(), a3.toString());
let b1 = B.create('jorge');
let b2 = new B('jorge');
let b3 = B.create2('jorge');
console.log(b1.toString(), b2.toString(), b3.toString());
@luislobo
Copy link
Author

luislobo commented Oct 17, 2017

returns

luis luis luis
B:jorge B:jorge jorge

Notice that the last 'jorge' does not have B:, because it calls new A()

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