Update : this answer is no longer correct. ECMAScript 2015 ( ECMA-262 6th ed. §§ 9.5, 26.2) has identified Proxy objects that can be used to achieve this.
In JavaScript engines that do not provide Proxy , this functionality is still not available. In these engines, the idioms that Lua will rely on __index and __newindex will have to be expressed in a different way, as shown below.
JavaScript looks more like a scheme than it does with smalltalk (which supports a method that is not defined) or lua. Unfortunately, your request is not supported as far as I know.
You can imitate this behavior with an extra step.
function CAD(object, methodName) // Check and Attach Default { if (!(object[methodName] && typeof object[methodName] == "function") && (object["__index"] && typeof object["__index"] == "function")) { object[methodName] = function() { return object.__index(methodName); }; } }
so your example becomes
function RPC(url) { this.url = url; } RPC.prototype.__index=function(methodname) //imagine that prototype.__index exists { AJAX.get(this.url+"?call="+ methodname); } var proxy = RPC("http://example.com/rpcinterface"); CAD(proxy, "ServerMethodA"); proxy.ServerMethodA(1,2,3); CAD(proxy, "ServerMethodB"); proxy.ServerMethodB("abc");
it would be possible to implement more functions in CAD, but this gives you an idea ... you can even use it as a call mechanism that calls a function with arguments if it exists, bypassing the extra step that I presented.
source share