Javascript元编程
有没有一种方法可以在javascript中指定类似于以下内容的内容Javascript元编程,javascript,metaprogramming,Javascript,Metaprogramming,有没有一种方法可以在javascript中指定类似于以下内容的内容 var c = {}; c.a = function() { } c.__call__ = function (function_name, args) { c[function_name] = function () { }; //it doesn't have to capture c... we can also have the obj passed in return c[function_name]
var c = {};
c.a = function() { }
c.__call__ = function (function_name, args) {
c[function_name] = function () { }; //it doesn't have to capture c... we can also have the obj passed in
return c[function_name](args);
}
c.a(); //calls c.a() directly
c.b(); //goes into c.__call__ because c.b() doesn't exist
没有。Mozilla实现了,但除此之外……没有。没有,不是真的。有一些替代方案——尽管没有您的示例那么好或方便 例如:
function MethodManager(object) {
var methods = {};
this.defineMethod = function (methodName, func) {
methods[methodName] = func;
};
this.call = function (methodName, args, thisp) {
var method = methods[methodName] = methods[methodName] || function () {};
return methods[methodName].apply(thisp || object, args);
};
}
var obj = new MethodManager({});
obj.defineMethod('hello', function (name) { console.log("hello " + name); });
obj.call('hello', ['world']);
// "hello world"
obj.call('dne');
近6年后,终于有了一种方法,使用:
const c=新代理({}{
获取(目标、关键){
如果(输入目标)返回目标[输入];
返回函数(){
log(`invoked${key}()来自代理`);
};
}
});
c、 a=函数(){
log('invoked a()');
};
c、 a();
c、 b()代码>