Last active
December 27, 2016 15:00
-
-
Save reinisriekstins/3bc63e786243dfbace408a64b1feadcc to your computer and use it in GitHub Desktop.
A way of creating static methods for a factory function in JavaScript.
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
| function Factory(config) { | |
| // do something with config obj... | |
| function doSomething(arg1, arg2) { | |
| console.log(arg1, arg2) | |
| } | |
| // static method | |
| // has to use the factory function's name, | |
| // can't use the 'this' keyword | |
| Factory.method = doSomething | |
| // object returned by factory | |
| return { | |
| method: doSomething, | |
| method2: () => doSomething(config.arg1, config.arg2) | |
| } | |
| } | |
| // usage example | |
| const obj = Factory({arg1: 'one', arg2: 'two'}) | |
| obj.method('eins', 'zwei') // => eins zwei | |
| obj.method2() // => one two | |
| Factory.method('uno', 'dos')// => uno dos |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment