function createFunction (name, args, body) {
var argumentsLength = arguments.length
, name
, args
, body
, isString = function (element) {return Object.prototype.toString.call(element) === '[object String]';};
if (argumentsLength === 0) {
name = '';
args = '';
body = '';
} else if (argumentsLength === 1) {
name = name;
args = '';
body = '';
if (!isString(name)) {throw new Error('Function name must be a string.');}
} else if (argumentsLength === 2) {
name = name;
body = args;
args = '';
if (!isString(name)) {throw new Error('Function name must be a string.');}
if (!isString(body)) {throw new Error('Function body must be a string.');}
} else if (argumentsLength === 3) {
name = name;
args = args;
body = body;
if (!isString(name)) {throw new Error('Function name must be a string.');}
if (!isString(args)) {throw new Error('Function arguments must be a string.');}
if (!isString(args)) {throw new Error('Function body must be a string.');}
}
return (new Function('return function ' + name + ' (' + args + ') {' + body + '};'))();
}
var func = createFunction ();
console.log(func.toString());
console.log(func());
var func = createFunction ('a');
console.log(func.toString());
console.log(func());
var func = createFunction ('a', 'return 1;');
console.log(func.toString());
console.log(func());
var func = createFunction ('a', 'b, c', 'return b + c;');
console.log(func.toString());
console.log(func(2, 3));
Комментариев нет:
Отправить комментарий