one*_*ach 9 javascript function object
创建函数通常很容易:
var f = function(){
alert("something");
};
Run Code Online (Sandbox Code Playgroud)
那么为什么有这样的Function对象:
var f = new Function("alert('something');");
Run Code Online (Sandbox Code Playgroud)
后者很难写/读.我只能提出一种情况,即有人在网页上键入一些JS代码并运行它.这也可以用eval
.
为何选择Function对象?
Rob*_*b W 15
该Function
对象可用于动态生成函数.
var some_fixed_value = 1;
var f = new Function("return " + some_fixed_value);
Run Code Online (Sandbox Code Playgroud)
反对:
var some_fixed_value = 1;
var f = function() {
return some_fixed_value;
};
// Break the function logic:
some_fixed_value = 'not_fixed_any_more!';
Run Code Online (Sandbox Code Playgroud)
或者,使用两个函数表达式:
var f = (function(copy_of_fixed_value) {
return function() {
return copy_of_fixed_value;
};
})(some_fixed_value);
Run Code Online (Sandbox Code Playgroud)
"这也可以通过以下方式解决eval
:"
var func_func = new Function('x', 'return x'); //function anonymous(x){return x}
var evil_func = eval('function(x){return x}'); //SyntaxError: function statement
// requires a name
var eval_func = eval('(function(x){return x})');//function(x){return x}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
2262 次 |
最近记录: |