2009-10-29 47 views
4

我想定义一个Javascript对象的行为,当被引用的属性/方法不存在时,这些对象将会启动。 在Lua中,您可以使用metatables和__index & __newindex方法来做到这一点。JavaScript原型有相当于Lua的__index&__newindex的东西吗?

--Lua code 
o = setmetatable({},{__index=function(self,key) 
    print("tried to undefined key",key) 
    return nil 
end 
}) 

所以我想知道如果在JavaScript中有类似的东西。

我试图做到的,是一个通用的RPC接口,它的工作原理是这样的(不是有效的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"); 

我怎么能这样做呢?

这可以完成吗?

+0

任何想法的人? – 2009-10-29 10:38:29

回答

3

的javascript更像是计划而不是像smalltalk(支持未定义的方法)或lua。不幸的是,您的请求并不支持我所知。

您可以通过额外的步骤来模拟此行为。

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); }; 
    } 
} 

所以你的榜样变得

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"); 

更多的功能可以在CAD中实现,但是这给你的想法......你甚至可以用它作为与参数,如果调用功能的调用机制它存在,绕过我介绍的额外步骤。

+0

我有点想象,JavaScript有一个__index,而我只是找不到它,但似乎我错了。感谢您的信息和窍门。这对我的目标来说已经足够了! – 2009-10-29 15:58:54

1

我假设你的实际需要比这个例子更复杂,因为你正在做什么与你传递给ServerMethodAServerMethodB参数,否则你只会做这样的事情

function RPC(url) 
{ 
    this.url = url; 
} 

RPC.prototype.callServerMethod = function(methodname, params) 
{ 
    AJAX.get(this.url+"?call="+ methodname); 
} 

var proxy = RPC("http://example.com/rpcinterface"); 
proxy.callServerMethod("ServerMethodA", [1,2,3]); 
proxy.callServerMethod("ServerMethodB", "abc"); 
4

仅供参考:Firefox支持非标准__noSuchMethod__扩展。

+0

感谢您的信息,不幸的是我需要跨浏览器兼容性,但很高兴知道,也许其他人将遵循套件 – 2009-10-30 13:50:29

相关问题