I want to define a behavior on Javascript objects that kicks in when the referenced attribute/method doesn't exist.
In Lua you can do this with metatables and the __index & __newindex
methods.
--Lua code
o = setmetatable({},{__index=function(self,key)
print("tried to undefined key",key)
return nil
end
})
So I'm wondering if there is something similar in javascript.
What I'm trying to achieve is a generic RPC interface that works like this (not valid Javascript):
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");
proxy.ServerMethodA(1,2,3);
proxy.ServerMethodB("abc");
So how can I do this?
Can this even be done?