Skip to content

Instantly share code, notes, and snippets.

@elxris
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 elxris/3e1dd57b8b17065de3f6 to your computer and use it in GitHub Desktop.
Save elxris/3e1dd57b8b17065de3f6 to your computer and use it in GitHub Desktop.
POO in JS
function MyClass (var1, var2) { // Constructor function
var privateVariable = 'foo'; // Private variable instanced
this.publicVariable = 'bar'; // Public variable instanced
this.privilegedMethod = function () {
return privateVariable; // It's privileged 'cause it can access private variable
};
}
// Only keept once on memory, available in all instance
MyClass.prototype.publicMethod = function () {
return this.privilegedMethod();
}
// Static variable, accesed only in MyClass.staticProperty
MyClass.staticProperty = 'foobar';
//...
var myInstance = new MyClass();
//undefined
myInstance.privateVariable;
//'bar'
myInstance.publicVariable;
//'foo'
myInstance.privilegedMethod();
//'foo'
myInstance.publicMethod();
//'foobar', but ...
MyClass.staticProperty;
//undefined
myInstance.staticProperty;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment