Last active
January 11, 2017 20:40
-
-
Save jion/fba7f0b0bee64f6cc212f7d58971c3ff to your computer and use it in GitHub Desktop.
Base template for create OOP classes in Javascript ES5
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
{ // MyClass | |
var MyClass = function () { | |
var self = this; | |
setupPublicProperties({ | |
publicVariable1: 'foo', | |
publicVariable2: 'bar', | |
}); | |
setupPrivateProperties({ | |
foo: 'bar', | |
man: 'uel', | |
car: 'los', | |
}); | |
var accessor = { | |
// Public properties via getter/setter | |
get: getter.bind(self), | |
set: setter.bind(self), | |
// Public methods | |
publicMethod1: method(self.method1), | |
publicMethod2: method(self.method2), | |
} | |
return accessor; | |
// Internals | |
function method(name) { | |
return function () { | |
return name.apply(self, arguments); | |
} | |
} | |
function getter(variable) { | |
return self.publicVariables[variable] !== undefined && self[variable]; | |
} | |
function setter(variable, value) { | |
self.publicVariables[variable] = self[variable] = value; | |
return self; | |
} | |
function setupPublicProperties(publicVariables) { | |
self.publicVariables = publicVariables; | |
for (key in publicVariables) { | |
self[key] = publicVariables[key]; | |
} | |
} | |
function setupPrivateProperties(privateVariables) { | |
self.privateVariables = privateVariables; | |
for (key in privateVariables) { | |
self[key] = privateVariables[key]; | |
} | |
} | |
}; | |
MyClass.prototype = { // Public & private methods | |
method1: function() { return this.privateMethod1() + this.publicVariables.publicVariable1 }, | |
method2: function() {}, | |
privateMethod1: function () { return 'privateMethod1'; }, | |
privateMethod2: function () { return 'privateMethod2'; }, | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment