Javascript:在运行时创建函数

时间:2017-10-24 15:27:17

标签: javascript lodash

更新

解决方案适用于foreach循环但不适用于for循环

function x(number){
  return number - 10;
}
var i = 0
var runtimefunctions = {};
var allLevels = {"1":"State","2":"Educational_Services","3":"Principal_Networks","4":"Schools"}
 for (var key in allLevels) {
   runtimefunctions[i] = function() { return x(i); };
i++;
};

console.log(runtimefunctions[1]()); // -6
console.log(runtimefunctions[2]()); // -6
console.log(runtimefunctions[3]()); // -6

努力创造功能,但它是第一次创造这样的东西,因此无法理解正确的方式......

我有一个功能..

function x(number){
return number - 10;
}
runtimefunctions = {};
now I have a loop to run
[1,2,3].forEach(function(y){
   //here I want to create a function.. which will make a function x(y) -- like this
   runtimefunctions[x] = new Function("return function x_" + levelIterator + "(levelIterator){ console.log(levelIterator); x(" + y + ") }")();

});

所以基本上......想要制作这样的功能。

runtimefunctions= {
 "1": x(1),
 "2": x(2),
and so on
}

3 个答案:

答案 0 :(得分:6)

这是你需要的吗?

function x(number){
  return number - 10;
}

var runtimefunctions = {};

[1,2,3].forEach(function(y){
   runtimefunctions[y] = function() { return x(y); };
});

console.log(runtimefunctions[1]()); // -9
console.log(runtimefunctions[2]()); // -8
console.log(runtimefunctions[3]()); // -7

要满足您的下一个( for-in )要求,您需要使用附加函数调用来关闭索引变量:

var runtimefunctions = {}, i = 0;
var allLevels = {"1":"State","2":"Educational_Services","3":"Principal_Networks","4":"Schools"}
for (var key in allLevels) {
  runtimefunctions[i] = function(index){ return function() { return x(index); } }(i++);
};

答案 1 :(得分:0)

这更容易。 例如:

const createFunctionWith = (x) => {
    return (param) => console.log(x, param)
}
let a = [1,2,3].map(x => createFunctionWith(x));
console.log(a[1]("bebe")); // 2, "bebe"

https://jsfiddle.net/muLxoxLd/

答案 2 :(得分:0)

你可以做这样的事情

// Found in your code
var x = (a) => {
    console.log(a)
};    

var runtimefunctions = {};

[1, 2, 3].forEach(function(y) {
    //Create a function with a parameter named "levelIterator"
    runtimefunctions[y] = Function("levelIterator", "{ console.log(levelIterator); x(" + y + ") }");

});

runtimefunctions[1]('test')