Last active
March 26, 2020 23:27
-
-
Save Integralist/8419151 to your computer and use it in GitHub Desktop.
Private and Privileged methods using the Constructor pattern in JavaScript
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
function Constructor(){ | |
this.foo = 'foo'; | |
// Needed for Private methods | |
var self = this; | |
// Private methods need to be placed inside the Constructor. | |
// Doesn't perform as well as prototype methods (as not shared across instances) | |
function private(){ | |
console.log('I am private'); | |
console.log(self.foo); | |
} | |
// Privileged methods need to be placed inside the Constructor. | |
// This is so they can get access to the Private methods. | |
this.privileged = function(){ | |
private(); | |
}; | |
} | |
Constructor.prototype.public = function(){ | |
console.log('I am public'); | |
}; | |
constructor = new Constructor; | |
console.log(constructor.foo); | |
constructor.public(); // will work | |
constructor.privileged(); // will work | |
constructor.private(); // won't work (can't be accessed directly) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@jslegers if you want to mimic Java/PHP you can use a lib like dejavu, which implements accessor keywords; or use a language that compiles into JavaScript - but to be honest I would just stick with plain JS and avoid real private methods. (easier to debug and to extend code if needed)
it's also good to remind that functional programming makes a few tasks way simpler and avoids bureaucracy. Not all the things needs to be a constructor! cheers.