Skip to content

Instantly share code, notes, and snippets.

@Integralist
Last active March 26, 2020 23:27
Show Gist options
  • Save Integralist/8419151 to your computer and use it in GitHub Desktop.
Save Integralist/8419151 to your computer and use it in GitHub Desktop.
Private and Privileged methods using the Constructor pattern in JavaScript
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)
@getify
Copy link

getify commented Jan 14, 2014

@jslegers

What does

count++; // Instance private properties

...purport to mean? You say that count++ is an example of "instance private properties", but of course that's not true. count (as you indicated in your other comment) is shared across all instances, or what you call a "singleton property". (btw, this seems like a strange usage of the word "singleton" which doesn't match with the typical definition of that word -- "shared" is a better, less confusing term here IMO).

So, if count is not actually an "instance private property", then what are examples of "instance private properties" that could be added here? In this pattern, how could you setup a private variable that only each instance could access (and not be shared across instances), that not only the kvs() "constructor" function could access, but all his member methods like set() and delete() could also access?

@millermedeiros
Copy link

@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)

"always bet on JS."

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.

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