javascript interactive

JavaScript Interactive — a console crash course


3.5 Function Objects

Warning: Your browser may be outdated or unsupported.

The JavaScript console is known to display some of the examples incorrectly in Internet Explorer 8 or older.
>>>
function test(a, b, c) {
    return [a, b, c];
}


  
>>>
test.call(null, 1, 2, 3)
[1, 2, 3]
The call() method is available for all function objects and provides an alternative way to calling it. The first argument is the object context, which will be explained further in the chapter on object-oriented programming.
>>>
var args = [1, 2, 3];


  
>>>
test.apply(null, args)
[1, 2, 3]
Similar to call(), the apply() method allows calling the function. Here the call arguments are provided in an array, which is more useful when the number of arguments varies or is unknown.
>>>
test.name + '/' + test.length
test/3
Function objects also have name and length properties, which are mostly useful for logging and debugging.
>>>
var anon = function () {};

  
>>>
anon.name
""
Naturally, anonymous functions do not have a very helpful name value.
>>>
function callerName() {
    return callerName.caller && callerName.caller.name;
}

  
Functions also have a caller property that is dynamically set to the calling function.
>>>
callerName()
null
When called from the global scope, the caller property is null.
>>>
(function whatIsMyName() { return callerName(); })()
"whatIsMyName"
Using a named function expression, we see that the caller property is set when called from a function scope.
>>>

Index 1 2 3 4 5 6 7 8 9