Skip to content

Instantly share code, notes, and snippets.

@Sjeiti
Last active August 29, 2015 14:15
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 Sjeiti/efeb5c03f599f5fd15e9 to your computer and use it in GitHub Desktop.
Save Sjeiti/efeb5c03f599f5fd15e9 to your computer and use it in GitHub Desktop.
An example of protected methods and prototypal inheritance
/**
* An example of protected methods and prototypal inheritance
* @requires lodash
* @param {string} name Call it something
* @param {object} extend An object with functions to override
* @returns {object}
*/
var baseFoo = (function(){
var basePrototype = {
protectedMethod: protectedMethod
,publicMethod: publicMethod
}
,baseProperties = {}
;
function protectedMethod(){
return 'protectedMethod';
}
function publicMethod(){
return 'publicMethod';
}
return function(name,extend){
var inst = Object.create(basePrototype,baseProperties);
_.extend(inst,{
name: name||'noName'
//
,expose: [] // The property the child object should return (could also be an object or a function).
,zuper: {} // Alas, super is reserved
});
//
// create super
for (var s in basePrototype) {
if (basePrototype.hasOwnProperty(s)) {
inst.zuper[s] = inst[s].bind(inst);
}
}
Object.freeze(inst.zuper); // Because we can
//
// extend the instance
if (extend) {
for (var fncName in extend) {
if (extend.hasOwnProperty(fncName)) {
inst[fncName] = extend[fncName].bind(inst);
}
}
}
//
// extend expose property with public methods
_.extend(inst.expose,{
publicMethod: inst.publicMethod.bind(inst)
});
//
// (do some more initialisation stuff like adding event listeners)
//
return inst;
}
})();
/**
* Here's a child object
*/
var childFoo = (function(){
// call the factory method to get an instance
var inst = baseFoo('childFoo',{
protectedMethod: protectedMethod
})
// add other public methods to the expose property
,expose = _.extend(inst.expose,{
otherPublicMethod: otherPublicMethod
})
,zuper = inst.zuper
// insert private variable here
;
function protectedMethod(){
return 'overriddenProtectedMethod'+zuper.protectedMethod();
}
function otherPublicMethod(){
return 'otherPublicMethod'+protectedMethod();
}
// return inst.expose not the instance itself
return expose;
})();
console.log(childFoo.publicMethod());
console.log(childFoo.otherPublicMethod());
console.log(childFoo.hasOwnProperty('publicMethod'));
console.log(childFoo.hasOwnProperty('protectedMethod'));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment