Created
November 20, 2015 13:33
-
-
Save ralekna/712d1c7fb480d30bf4f4 to your computer and use it in GitHub Desktop.
A JavaScript construct for having private instance fields
This file contains 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 PrivateFactory(scope) { | |
scope._ = function(fn) { | |
return function() { | |
return fn.apply(scope, arguments) | |
} | |
} | |
} | |
var Greeter = (function() { | |
function myPrivateMethod(greeting) { | |
return greeting + ", " + this.name; | |
} | |
function Greeter(name) { | |
PrivateFactory(this); | |
this.name = name; | |
} | |
Greeter.prototype.greet = function greet(greeting) { | |
console.log(this._(myPrivateMethod)('Hello')); | |
} | |
return Greeter; | |
})(); | |
var greeter = new Greeter('John'); | |
greeter.greet('Hello'); // output: "Hello, John" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment