先搞清楚如下几个案例
案例1
//
function myFun(){
return Function('return ' + 8899)();
}
console.log(myFun()); //8899
运行结果如下:
案例2
//在js中,void是一个操作符
console.log(void (6), void (0), void (1), void ("hello"), void (true), void (57.68));
console.log(void 6, void 0, void 1, void "hello", void true, void 57.68);
//eval()函数
//js中eval()函数参考网页https://www.w3school.com.cn/js/jsref_eval.asp
console.log("*1*", eval(666)); //666
console.log("*2*", eval("8888")); //8888
console.log("*3*", eval("2 + 3")); //5
console.log("*4*", eval(5 * 10)); //50
var x = 6;
console.log("*5*", eval(x * 10)); //60
console.log("*6*", eval("x" * 7)); //NaN
// console.log(eval("tom")); //报错,tom is not defined
console.log("*7*", eval("function yes(){return 321;}")); //undefined
console.log("*7B*", eval("function yes(){}")); //undefined
console.log("*7C*", eval("(function yes(){})")); //ƒ yes(){}
console.log("*8*", eval("(function yes(){return 321;})")); //ƒ yes(){return 321;}
console.log("*9*", eval("(" + "function yes(){return 321;}" + "()" + ")")); //321
function ok(){return 321;}
console.log("*10*", eval("ok")); //ƒ ok(){return 321;}
console.log("*11*", eval(ok)); //ƒ ok(){return 321;}
运行结果如下:
案例3
var ask = function() {
return "I love china";
}
console.log("*12*", eval("ask")); //ƒ () {return "I love china";}
console.log("*13*", eval(ask)); //ƒ () {return "I love china";}
console.log("*14*", eval("(" + ask + "()" + ")")); //I love china
//
function myFun(){
return Function('return ' + '6666')();
// return Function('return ' + 'tom')(); //报错,tom is not defined
// return Function('return ' + 'hello')();
}
console.log(myFun()); //6666
//
var s1 = 'function fn1(){return "江西省赣州市于都县";}';
//
function myFun2(){
return Function('return ' + s1 + "()")();
}
console.log(myFun2()); //江西省赣州市于都县
function myFun3(){
return Function('return ' + s1)();
}
console.log(myFun3()); //ƒ fn1(){return "江西省赣州市于都县";}
运行结果如下:
案例4(把json字符串转换为json对象,json字符串中包含js函数)
var strJson = '{"id" : 78, "formate" : "function test(){ return 23;}"}';
var jsonObj = JSON.parse(strJson, hello);
var jsonObj2 = JSON.parse(strJson);
console.log("15", jsonObj2, jsonObj2.id, typeof jsonObj2.id, jsonObj2.formate, typeof jsonObj2.formate);
console.log("*16*", jsonObj, typeof jsonObj, jsonObj.id, jsonObj.formate, typeof jsonObj.formate);
function hello(key, value) {
console.log("-----", "key=" + key, "value=" + value, "value的类型" + (typeof value));
if (key == 'formatter' && "string" == typeof value
&& value.indexOf('function') == 0) {
return Function('return ' + value)();
}
return value;
}
console.log("*17*", jsonObj, jsonObj.id, jsonObj.formate, typeof jsonObj.formate);
//
console.log(eval("(" + jsonObj.formate + "()" + ")")); //23
运行结果如下: