我希望我的用户可以创建自己的与特定对象一起使用的格式函数。我找到了两种方法,但我不知道这些功能是否可以被黑客入侵。它在 nodeJS 中运行。
//First way with eval (evil ?)
function convertObj(formula) {
return function (obj) {
return eval(formula);
};
}
// Second way with function (same as eval ?)
function convertObj2(formula) {
return new Function("obj", "return " + formula);
}
var inst = {
"name": "BOB",
"age": "30"
};
var formula = "obj.name.toLowerCase() + ' is ' + obj.age + ' years old'";
var next = convertObj(formula);
var next2 = convertObj2(formula);
document.write('<p>' + next(inst) + '</p>');
document.write('<p>' + next2(inst) + '</p>');
打印
bob is 30 years old
bob is 30 years old