This tutorial will help to understand the different ways of invoking functions in Javascript. The another term we use for invoking function is "calling a function". Functions can be invoked in different ways as below:
Let us create a file Invoke.html
1-Common way of invoking functions in Javascript
<html>
<head><title></title>
<script type= text/javascript>
function multiplyFun(a, b) {
return a * b;
}
</script>
</head>
<body>
</body>
</html>
Here the function multiplyFun belongs to the default object (i.e. window object).
Now we will invoke function "multiplyFun" of window object.
multiplyFun(a, b);
Invoking functions in this fashion is not used as to avoid name conflicts among global variables and
methods.
2- To avoid the conflicts we use a global default object i.e. this
Example:
function testFunction() {
console.log(this); // object : Window invoke.html
}
testFunction();
Here this refers to the global object.
3- As in javascript we consider everything as an object. Hence we consider a function as an object.
For example:
var testFunction = {
country:"India",
state: "Rajasthan",
address: countryName () {
return this.country + " " + this.state;
}
}
testFunction.countryName(); // Will return "India"
Here the function countryName belongs to an object testFunction and this represents the object testFunction and it owns the code inside the object testFunction hence it will make use of local variables and the methods.
4- Invoking a function with constructor
Here we use a new keyword to create an object .
// A function constructor:
function myFunction(x, y) {
this.country = x;
this.state = y;
}
// creating a new object
var obj = new myFunction("India","Rajasthan");
obj.country; // Will return "India"
obj.state; // Will return Rajasthan
5- Invoking a Function using an built-in function call()
We can invoke a javascript function by the use of the builtin funciton of javascript i.e. call().
Here we pass Array as an argument
function testFunction(a, b) {
return a * b;
}
testObject = testFunction.call(testObject, 52, 2); // Will return 104
6- Invoking a Function using an built-in function apply()
We can also invoke a javascript function by the use of the builtin function of javascript i.e. apply().
In call() function the arguments are separated by a comma .
function testFunction(a, b) {
return a * b;
}
myArray = [100, 4];
testObject = testFunction.apply(testObject, myArray); // Will also return 400
Note : In both the invocation process the first argument is the owner object itself (i.e. testObject)
0 Comment(s)