Rob*_*uld 4 javascript lua prototype
我想在引用的属性/方法不存在时启动的Javascript对象上定义一种行为。在Lua中,您可以使用元表和__index & __newindex方法来执行此操作。
--Lua code
o = setmetatable({},{__index=function(self,key)
print("tried to undefined key",key)
return nil
end
})
Run Code Online (Sandbox Code Playgroud)
所以我想知道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");
Run Code Online (Sandbox Code Playgroud)
那我该怎么做呢?
可以做到吗?
更新:这个答案不再正确。ECMAScript 2015 ( ECMA-262 6th Ed. \xc2\xa7\xc2\xa7 9.5, 26.2) 定义的Proxy对象,可用于实现此目的。
在不提供 的 JavaScript 引擎中Proxy,此功能仍然不可用。在这些引擎中,Lua 中依赖的习语__index必须__newindex以其他方式表达,如下所示。
javascript 更像是scheme,而不是smalltalk(支持未定义的方法)或lua。不幸的是,据我所知,您的请求未得到支持。
\n\n您可以通过额外的步骤来模拟此行为。
\n\nfunction CAD(object, methodName) // Check and Attach Default\n{\n if (!(object[methodName] && typeof object[methodName] == "function") &&\n (object["__index"] && typeof object["__index"] == "function")) {\n object[methodName] = function() { return object.__index(methodName); };\n }\n}\nRun Code Online (Sandbox Code Playgroud)\n\n所以你的例子变成
\n\nfunction RPC(url)\n{\n this.url = url;\n}\n\nRPC.prototype.__index=function(methodname) //imagine that prototype.__index exists\n{ \n AJAX.get(this.url+"?call="+ methodname);\n}\n\nvar proxy = RPC("http://example.com/rpcinterface");\nCAD(proxy, "ServerMethodA");\nproxy.ServerMethodA(1,2,3);\nCAD(proxy, "ServerMethodB");\nproxy.ServerMethodB("abc");\nRun Code Online (Sandbox Code Playgroud)\n\nCAD 中可以实现更多功能,但这给了您这样的想法...您甚至可以将其用作调用机制,通过参数调用函数(如果存在),从而绕过我介绍的额外步骤。
\n