Last active
April 9, 2016 21:20
-
-
Save amonks/0d6de702cf41cd296aa2d01ef6bb4d36 to your computer and use it in GitHub Desktop.
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
// here's a module with public and private members using the constructor pattern | |
// see here: http://javascript.crockford.com/private.html | |
var A_Module = function () { | |
// this hello function is public | |
public_api = { hello: function () { return "hello" } } | |
// this function is private | |
function times(a, b) { return a * b } | |
// this function is public | |
// this is the same as if we'd put this definition within the public_api object above (like `hello` is) | |
public_api.square = function (a) { return times(a, a) } | |
return public_api | |
} | |
// here's how we'd use that module. | |
// first construct it: | |
let the_module = new A_Module() | |
the_module.square(5) // 25 | |
the_module.hello() // "hello" | |
the_module.times // undefined | |
// here's an equivalent module using the revealing module pattern with es6 features | |
// this is what Crockford does these days | |
function another_module() { | |
times = function (a, b) { | |
return a * b | |
} | |
square = function (a) { | |
return times(a, a) | |
} | |
hello = function () { | |
return "hello" | |
} | |
return Object.freeze({ | |
square, hello | |
}) | |
} | |
// and here's how we'd use it | |
// this time we *don't* need the `new` keyword | |
let the_module = another_module() | |
the_module.square(5) // 25 | |
the_module.hello() // "hello" | |
the_module.times // undefinedthe_module |
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
// let's try the second example | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment