Skip to content

Instantly share code, notes, and snippets.

@ralekna
Created November 20, 2015 13:33
Show Gist options
  • Save ralekna/712d1c7fb480d30bf4f4 to your computer and use it in GitHub Desktop.
Save ralekna/712d1c7fb480d30bf4f4 to your computer and use it in GitHub Desktop.
A JavaScript construct for having private instance fields
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