Created
May 27, 2013 12:40
-
-
Save destan/5656866 to your computer and use it in GitHub Desktop.
Private prototype functions and provate memebers in native javascript.
This file contains 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
// Closure is necessary to get rid of 'strict mode' as `args.callee.caller` cannot be used in 'strict mode' | |
(function (scope) { | |
// LeClass declaration | |
// =================== | |
scope.LeClass = function () { | |
// Private members declared in private namespace `prv` | |
var prv = { | |
trala: 'you touch my tralala...', | |
ding: 'my ding ding dong...' | |
}; | |
// `getter` for private members. This function needs to be declared here instead of in prototype | |
// in order to get access to `prv` | |
this._get = function(variableName) { | |
checkAccessibility.apply(this, [arguments]); | |
return prv[variableName] | |
} | |
// Private methods can also be called from the constructer | |
this.privateMethodTralala(); | |
}; | |
LeClass.prototype.publicMethod = function (item) { | |
// Private methods of class `LeClass` are only accessible from LeClass' public methods | |
this.privateMethodTralala(); | |
}; | |
LeClass.prototype.privateMethodTralala = function (item) { | |
checkAccessibility.apply(this, [arguments]); | |
console.log(this._get('trala') + ' ' +this._get('ding')); | |
}; | |
function checkAccessibility(args) { | |
var prototyp = Object.getPrototypeOf(this); | |
if (args.callee.caller == prototyp.constructor) { | |
return; | |
} | |
for (var key in prototyp) { | |
if (prototyp.hasOwnProperty(key)) { | |
if (prototyp[key] == args.callee.caller) { | |
return; | |
} | |
} | |
} | |
throw 'Access violation, this function is private'; | |
} | |
return; | |
}(window)); | |
// Show time | |
// --------- | |
var myObject = new LeClass(); | |
// This will succeed | |
myObject.publicMethod(); | |
// Those will fail | |
try{ | |
myObject.privateMethodTralala(); | |
} | |
catch(e){ | |
console.error(e); | |
} | |
console.log(myObject._get('trala')); | |
// Expected output | |
// --------------- | |
// you touch my tralala... my ding ding dong... | |
// you touch my tralala... my ding ding dong... | |
// Access violation, this function is private | |
// Uncaught Access violation, this function is private |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment