是的, 并且是es5就已经只支持的.
因为函数和变量一样, 默认是全局变量的子元素, 并且子元素除了用点'.'调用外,还可以用数组方括号[]调用. 区别是方括号内是写字符串的.

p = console.log //省字数
function x(){p('x')}
function y(){p('y')}
f = 'x'

这时候, window.x === window['x'] 都是x函数.(在node中window甩global替换) 于是可以这样调用

window[f]() // 输出x
f = 'y'
window[f]() // 输出y

这样执行相同的指令window[f]可以实际执行不同的函数x,y
参考how-to-execute-a-javascript-function-when-i-have-its-name-as-a-string
后面有一个回答很有价值的, 就是将函数的点链式调用写在字符串里面,复制过来,感觉如果和科里化/pointfree结合会很有用, 似乎能创造一种自然语言一般的编程方式.

来自Jason Bunting的回答:

Don't use eval unless you absolutely, positively have no other choice.

As has been mentioned, using something like this would be the best way to do it:

window["functionName"](arguments);

That, however, will not work with a namespace'd function:

window["My.Namespace.functionName"](arguments); // fail

This is how you would do that:

window["My"]["Namespace"]["functionName"](arguments); // succeeds

In order to make that easier and provide some flexibility, here is a convenience function:

function executeFunctionByName(functionName, context /*, args */) {
  var args = [].slice.call(arguments).splice(2);
  var namespaces = functionName.split(".");
  var func = namespaces.pop();
  for(var i = 0; i < namespaces.length; i++) {
    context = context[namespaces[i]];
  }
  return context[func].apply(context, args);
}

You would call it like so:

executeFunctionByName("My.Namespace.functionName", window, arguments);

Note, you can pass in whatever context you want, so this would do the same as above:

executeFunctionByName("Namespace.functionName", My, arguments);

如果把上面的My.Namespace.functionName改成My Namespace FunctionName是不是就像是自然语言了?

标签: none 阅读量: 1359

添加新评论