Last active
December 28, 2015 09:39
-
-
Save tenorok/7480866 to your computer and use it in GitHub Desktop.
JavaScript: Private properties
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
/* Constructor */ | |
function Klass(text, separator) { | |
this.text = text; | |
this.separator = separator; | |
this.__bind(); // Set context to private methods | |
} | |
Klass.prototype = (function() { | |
/* Private properties */ | |
var _ = { | |
privateField: 'World', | |
privateMethod: function() { | |
return this.separator + _.privateField + Klass.staticMethod() + $.privateStaticMethod(); | |
} | |
}; | |
/* Private static properties */ | |
var $ = { | |
privateStaticMethod: function() { | |
return ' =)'; | |
} | |
}; | |
/* Public properties */ | |
var properties = { | |
publicMethod: function() { | |
return this.text + _.privateMethod(); | |
} | |
}; | |
/** | |
* Set context to private methods | |
* @private | |
*/ | |
properties.__bind = function() { | |
for(var prop in _) if(_.hasOwnProperty(prop) && typeof _[prop] === 'function') { | |
_[prop] = _[prop].bind(this); | |
} | |
}; | |
return properties; | |
})(); | |
/* Public static properties */ | |
Klass.staticMethod = function() { | |
return '!'; | |
}; | |
console.log(new Klass('Hello', ', ').publicMethod()); // Hello, World! =) | |
console.log(Klass.staticMethod()); // ! |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment