Javascript元编程 [英] Javascript Metaprogramming

查看:92
本文介绍了Javascript元编程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法在javascript中指定类似于以下内容的内容?

Is there a way to specify something similar to the following in 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](args);
}

c.a(); //calls c.a() directly
c.b(); //goes into c.__call__ because c.b() doesn't exist

推荐答案

不,不是.有一些替代方法-尽管不如您的示例好或方便.

No, not really. There are some alternatives - though not as nice or convenient as your example.

例如:

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

这篇关于Javascript元编程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆