It is common and easy to create function like:
var f = function(){
alert("something");
};
So why is there Function object like:
var f = new Function("alert('something');");
The latter is hard to write/read. I can only come up with one situation in which someone typing some JS code to the webpage and running it. This can also be solved with eval
.
Why Function object?
Function objects provide two main advantages over a straight function call. The first is that a function object can contain state. The second is that a function object is a type and therefore can be used as a template parameter.
In JavaScript, functions are first-class objects, because they can have properties and methods just like any other object. What distinguishes them from other objects is that functions can be called. In brief, they are Function objects.
We can do without the function keyword in today's JavaScript code. We can use arrow functions for functions that don't need to reference this and use the method shorthand for anything that needs to reference this .
An object is a collection of functions and data. A function is a collection of commands and data. When a bunch of functions work together to perform a certain task we may call this community of functionality an object.
The Function
object can be used to dynamically generate functions.
var some_fixed_value = 1;
var f = new Function("return " + some_fixed_value);
Opposed to:
var some_fixed_value = 1;
var f = function() {
return some_fixed_value;
};
// Break the function logic:
some_fixed_value = 'not_fixed_any_more!';
or, using two function expressions:
var f = (function(copy_of_fixed_value) {
return function() {
return copy_of_fixed_value;
};
})(some_fixed_value);
"This can also be solved with 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}
The Function (with capital F) is not a keyword, it's a base class for any other functions in JavaScript, given the fact that everything in JavaScript is an object, functions should/must inherit from a base class that represents base functionality of all other functions (methods/classes).
You can play a lot with function inheritance via Function's prototype:
here's an example to define a .run method for all functions in JS:
Function.prototype.run = function (delay) {
setTimeout(this, delay);
};
test:
function test(){console.log("test")};
test.run(2000);
there's an undocumented __proto__
property that points to the base-class prototype, you can check it on each instance of function:
test.__proto__ == Function.prototype; // true
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With