Invoking Functions
JavaScript functions can be invoked in four ways:
- as functions,
- as methods,
- as constructors, and
- indirectly through their call() and apply() methods.
Function Invocation
var total = distance(0,0,2,1) + distance(2,1,3,5);
Method Invocation
A method is nothing more than a JavaScript function that is stored in a property of an object.
var calculator = {
operand1: 1,
operand2: 1,
add: function() {
// Note the use of the this keyword to refer to this object.
this.result = this.operand1 + this.operand2;
}
};
calculator.add();
Constructor Invocation
If a function or method invocation is preceded by the keyword new, then it is a constructor invocation.
var o = new Object();
Indirect Invocation
call() and apply() allow you to indirectly invoke a function as if it were a method of some other object.
To invoke the function f() as a method of the object o (passing no arguments), you could use either call() or apply():
f.call(o);
f.apply(o);
to pass two numbers to the function f() and invoke it as if it were a method of the object o, you could use code like this:
f.call(o, 1, 2);
The apply() method is like the call() method, except that the arguments to be passed to the function are specified as an array:
f.apply(o, [1,2]);