Function expressions and function declarations
Since you are interested in functions, here is some important stuff to know.
var abc = function() { ... }
is known as a function expression. The variable will be assigned that anonymous function at execution time, though its variable declaration will be hoisted to the top of the current execution context (scope).
However, a function expression can be given a name too, so that it can be called within its body to make it recursive. Keep in mind IE has some issues with this. When you assign it a name, it is most definitely not an anonymous function.
A function such as function abc() { ... }
is known as a function declaration. Its definition is hoisted to the top of its scope. Its name is available within it and its parent's scope.
Further Reading.
Your Example
It is an anonymous function, but assigned to the variable sayHi
.
As ?ime Vidas mentions, a new Function
object is instantiated with the new
operator, and the arguments and function body are passed in as strings. The resulting object is assigned to sayHi
.
The real world use of creating a function using this method is rare (though it may be just to help show that functions are objects). I also believe passing its arguments list and function body as a string will invoke an eval()
type function, which is rarely good when a much better construct is available.
Also, functions created with Function
do not form a closure.
I would only use this method if for some reason I needed to create a Function
with its arguments and/or body only available to me as a string.
In the real world, you'd do...
var sayHi = function(toWhom) {
alert('Hi' + toWhom);
};
Also refer to comments by Felix and ?ime for good discussion and further clarification.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…