如果要使用Function构造函数创建克隆,则应执行以下操作:
_cloneFunction = function(_function){
var _arguments, _body, _result;
var _regexFunction = /^function[\s]+[\w]*\(([\w\s,_\$]*)?\)\{(.*)\}$/;
var _regexArguments = /((?!=^|,)([\w\$_]))+/g;
var _matches = _function.toString().match(_regexFunction)
if(_matches){
if(_matches[1]){
_result = _matches[1].match(_regexArguments);
}else{
_result = [];
}
_result.push(_matches[2]);
}else{
_result = [];
}
var _clone = Function.apply(Function, _result);
// if you want to add attached properties
for(var _key in _function){
_clone[_key] = _function[_key];
}
return _clone;
}
一个简单的测试:
(function(){
var _clone, _functions, _key, _subKey;
_functions = [
function(){ return 'anonymous function'; }
,function Foo(){ return 'named function'; }
,function Bar(){ var a = function(){ return 'function with internal function declaration'; }; return a; }
,function Biz(a,boo,c){ return 'function with parameters'; }
];
_functions[0].a = 'a';
_functions[0].b = 'b';
_functions[1].b = 'b';
for(_key in _functions){
_clone = window._cloneFunction(_functions[_key]);
console.log(_clone.toString(), _clone);
console.log('keys:');
for(_subKey in _clone){
console.log('\t', _subKey, ': ', _clone[_subKey]);
}
}
})()
这些克隆将丢失其名称和范围,但不会覆盖任何封闭变量。