这有效:

var i = 'foo';
eval('function '+i+'(param) { this.param = param; return this; }');
console.log(foo); // [Function: foo]

这不是:
['bar', 'quux'].forEach(function(i) {
    eval('function '+i+'(param) { this.param = param; return this; }');
});
console.log(bar); // ReferenceError: bar is not defined

显然,forEach函数或其从属范围使事情变得困惑。我检查了bar函数在此期间是否可用,但无法在外部生存。

最佳答案

['bar', 'quux'].forEach(function(i) {
    this.eval('function '+i+'(param) { this.param = param; return this; }');
});

['bar', 'quux'].forEach(function(i) {
    window.eval('function '+i+'(param) { this.param = param; return this; }');
});

['bar', 'quux'].forEach(function(i) {
  eval.call(null, 'function ' + i + '(param) { this.param = param; return this; }');
  // same
  // eval.call(window, 'function ' + i + '(param) { this.param = param; return this; }');
});

关于javascript - 如何动态创建命名函数而不考虑作用域?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/27000409/

10-16 20:03