|Tuesday, 10 August 2010|
Page 1 of 3
There are, at least, three distinct ways of creating a function and this does nothing to make understanding easy.
The first way is to use the function statement. This is the most commonly used way of creating a function and the one that beginners are generally taught (and should be taught first):
In this case myfunc1 is a “function name” and not a simple variable.
The second is to use the function operator:
var myfunc2 = function(a)
var myfunc3 = new Function(
That is, the Function constructor accepts a variable number of string parameters – the last of which is the function body and the remainder are functions. Also notice that Function is always treated as if it had been written as new Function, i.e. it always creates a new object.
All three ways create a function that you can call in the same way, e.g. myfunc1(34) etc. From this point of view they are identical.
However, the first creates a function variable and the second just a standard variable that references a function. You can use the second form to create a function variable as well if you want to:
var myfunc2 = function myfunc4(a)
Now you can call the same function using myfunc2 or myfunc4. You can think of the function operator as being used in both cases such that it defines a function variable if one is provided and a standard reference variable if one is used.
The big difference is between the first two and the third. This creates a function object on the fly in the sense that its parameters are strings that might well be constructed at run time rather than compile time.
If you are worried about efficiency don’t use the Function constructor.
Functions as object
Functions, no matter how they are defined are objects. You can treat them as objects without exception. For example if you you want to add a property to a function then you can:
In this case we have added the argcount property to the function object myfunction and displayed its value.
What might seem even stranger is that a function object can have methods. Yes that's correct a function can have functions. For example, the getargcount method works as you would expect:
The Function object has a range of built in properties and methods. For example, the toString method returns the source of a function as a string:
There is a length property that returns the number of arguments in the function.
Also notice that there are some properties that only make sense when used while the function is being evaluated. For example, the arguments property gives an object which contains the arguments actually used in a call. If you try and make use of this property outside of the function then it is null - which is reasonable.
|Last Updated ( Thursday, 19 August 2010 )|