第七章、运行时求值

用eval()方法进行求值

eval()方法将执行传入的代码的字符串,并在调用eval()方法的作用域内进行代码求值,最后返回传入字符串中最后一个表达式的执行结果。

console.log(eval("5 + 5"));  // 10
eval("var a = 5;");
console.log(a);  // 5

// 仅在调用eval()方法的作用域内进行求值
(function () {
	eval("var a = 6");
    console.log(a);  // 6
})();
console.log(a);  // 5

// 返回最后一个表达式的执行结果
var b = eval("3+4; 5+6");
console.log(b); // 11
1
2
3
4
5
6
7
8
9
10
11
12
13
14

在全局作用域内求值操作

eval()方法求值的作用域就是调用eval()时的作用域,要让代码字符串在全局作用域内进行求值,可以将代码字符串放在动态生成的<script>标签内,并将其插入到文档中。

function globalEval(data) {
    // 去除字符串前后空格
    data= data.replace(/^\s*|\s*$/g,"");
    if(data){
        var head = document.getElementsByTagName("head")[0] || document.documentElement;
        var script = document.createElement("script");
        // 创建script节点
        script.tpye = "text/javascript";
        script.text = data;
        // 将节点附加到DOM上,再去除它
        head.appendChild(script);
        head.removeChild(script);
    }
}

globalEval("var a = 1");
console.log(window.a);  // 1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17

查找函数的参数名称

使用函数的toString()方法可以返回函数的原始文本,并且包含原始声明的所有空格,包括行结束符。

function getArgumentName(fn) {
	var found = /^[\s(]*function[^(]*\(\s*([^)]*?)\s*\)/.exec(fn.toString());
	return found && found[1] ? found[1].split(/,\s*/) : [];
}
function a(x, y, z) {}
console.log(getArgumentName(a)); // ["x", "y", "z"]
1
2
3
4
5
6