Last active
August 29, 2015 14:06
-
-
Save hypesystem/161a9dcb96854e9ec39a to your computer and use it in GitHub Desktop.
Private scope in node.js / dirty, dirty trick to get private methods
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
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; |
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
Notice that privateFunction is nowhere to be found on the object, but it still logs, and has access to
this
.