Proxy class javascript
by Douglas Enas
JavaScript
var defineClass = (function() {
// Creates a proxying function that will call the real object.
function createProxyFunction(functionName) {
return function() {
// 'this' in here is the proxy object.
var realObject = this.__realObject__,
realFunction = realObject[functionName];
// Call the real function on the real object, passing any arguments we received.
return realFunction.apply(realObject, arguments);
};
};
// createProxyClass creates a function that will create Proxy objects.
// publicFunctions: an object of public functions for the proxy.
function createProxyClass(publicFunctions) {
var ProxyClass, functionName, func;
// This is this Proxy object constructor.
ProxyClass = function (realObject) {
// Choose a reasonably obscure name for the real object property.
// It should avoid any conflict with the public function names.
// Also any code being naughty by using this property is quickly spotted!
this.__realObject__ = realObject;
};
// Create a proxy function for each of the public functions.
for (functionName in publicFunctions) {
func = publicFunctions[functionName];
// We only want functions that are defined directly on the publicFunctions object.
if (publicFunctions.hasOwnProperty(functionName) &&
typeof func === "function") {
ProxyClass.prototype[functionName] = createProxyFunction(functionName);
}
}
return ProxyClass;
}
function copyToPrototype(source, destination) {
var prototype = destination.prototype,
property;
for (property in source) {
if (source.hasOwnProperty(property)) {
prototype[property] = source[property];
}
}
};
function...