Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do Javascript prototypes have something equivalent to Lua's __index & __newindex?

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?

like image 441
Robert Gould Avatar asked Oct 29 '09 07:10

Robert Gould


1 Answers

Just FYI: Firefox supports a non-standard __noSuchMethod__ extension.

like image 175
Miles Avatar answered Sep 22 '22 03:09

Miles