[var | Namespace.]ClassName = (function(Class) {
/* Any static(class-wide) privates go here */
var privateMethod = function() {
return 'I\'m doing something privately';
};
/* The class prototype */
Class.prototype = {}; // or new BaseClass();
Class.prototype.propertyName = function(value) {
var returnValue;
// Unlock private Access
this.privateAccess = true;
// Forward the property access
returnValue = this.privateAccessFunction('propertyName', value);
// Lock it back up again!
delete this.privateAccess;
return returnValue;
};
// Lock the function, so it can't be modified.
Object.freeze(Class.prototype.propertyName);
// Optional: Lock the prototype
/* The class constructor */
Class.instance = function(config) {
// Fail if called without using new!
if (!this instanceof Class)
return undefined;
// So derivative classes don't share privates
if (config) {
var myPrivateMembers = {
propertyName: 'value'
};
Object.defineProperty(
this,
'privatePropertyAccess''privateAccessFunction',
{
//This is the actual Getter/Setter
// P.S. I like chainable properties
value: function(name, value) {
// Protects our function from call(obj)
if (!this.privateAccess || !this instanceof Class)
return undefined;
if (name !== undefined && typeof name === 'string') {
if (value !== undefined) {
myPrivateMembers[name] = value;
return this;
}
return myPrivateMembers[name];
}
return undefined;
},
writable: false,
configurable: false,
enumerable: false
}
);
}
};
// So that we get the Class back
return Class;
}([Namespace.]ClassName = [Namespace.]ClassName || function(config){
if (this instanceof [Namespace.]ClassName)
return [Namespace.]ClassName.instance.call(this, config);
}));
Fuzzical Logic
- 139
- 10
Malachi
- 28.7k
- 11
- 86
- 188