Skip to content

Instantly share code, notes, and snippets.

@hypesystem
Last active August 29, 2015 14:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hypesystem/161a9dcb96854e9ec39a to your computer and use it in GitHub Desktop.
Save hypesystem/161a9dcb96854e9ec39a to your computer and use it in GitHub Desktop.
Private scope in node.js / dirty, dirty trick to get private methods
var PublicClass = function() {
this.state = "something";
}
PublicClass.prototype.publicMethod = function() {
privateFunction.call(this); //<-- this is a dirty, dirty trick, running *privateFunction* as a private method
};
function privateFunction() {
console.log(this.state); //<-- in order to make *this* accessible, we need to use the trick above
}
module.exports = PublicClass;
@hypesystem
Copy link
Author

var PublicClass = require("public-class.js");
console.log(new PublicClass());
// => PublicClass {state: "something", publicMethod: function}

Notice that privateFunction is nowhere to be found on the object, but it still logs, and has access to this.

var obj = new PublicClass();
obj.publicMethod();
// => something

@hypesystem
Copy link
Author

WHY? It removes the need for globally scoped module variables (as everything can now be set as an attribtute on this), as the variables with global scope are undesireable and unpredictable.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment