Created
October 17, 2017 16:45
-
-
Save luislobo/4451e141655d7ba55548cbdc29e577d0 to your computer and use it in GitHub Desktop.
How to create ES6 static methods that create objects of itself
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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()); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
returns
Notice that the last 'jorge' does not have B:, because it calls
new A()