There are two (mostly) equivalent ways to define a function:
function Add(a, b) { return a + b };
var Add = function(a, b) { return a + b };
As far as I know the only semantic difference is in the output of
Add.toString(), and some browsers fail to recognise the name in the second
case and display anonymous function
in stack traces.
There are 2 main ways to call a function:
Add(1, 2);
In this case, no context is provided, so when Add
is running, this
will be the default context. This is usually window
or similar but varies on implementation and ECMA strictness/version. Do not rely on this
in Add
And these two equivalent methods:
Add.call (something, 1, 2);
Add.apply(something, [1, 2]);
When Add runs in both calls, this
will be the value of something
.
If something is null
or undefined, depending on the strictness etc, it may be window
or similar, or null
. Do not rely on this
in Add
When a function is a property of an object, a short-hand call me be used:
var Obj = { };
Obj['Add'] = Add;
Obj.Add (1, 2);
Obj['Add'](1, 2);
var name = 'Add';
Obj[name] (1, 2);
With both syntaxes, when Add
is running, this
will point to Obj
.
This may be overriden, for instance since the following is not a shorthand
call (such as O.F()
or O[F]()
), something
is the value used:
Obj.Add.call(something, 1, 2)