function call()
Description
functionName.call() calls the function with this
value,
and set this
inside the function body.
The first argument is the this value, and the remaining arguments must be enumerated specifically.
Example
function sum(num1, num2){//from w w w.j ava 2s. co m
return num1 + num2;
}
function callSum(num1, num2){
return sum.call(this, num1, num2);
}
console.log(callSum(10,10)); //20
The code above generates the following result.
Augment this
call() can augment the this value inside of the function.
<!-- w w w . j av a 2 s. com-->
<!DOCTYPE HTML>
<html>
<head>
<script type="text/javascript">
window.myName = "XML";
var o = { myName: "CSS" };
function printMyName(){
console.log(this.myName);
}
printMyName(); //XML
printMyName.call(this); //XML
printMyName.call(window); //XML
printMyName.call(o); //CSS
</script>
</head>
<body>
</body>
</html>
printMyName() is defined as a global function, and when it's called in the global scope, it displays "XML" because this.myName evaluates to window.myName.
You can then call the function explicitly in the global scope by using printMyName.call(this) and printMyName.call(window), which both display "XML". Running printMyName.call(o) switches the context of the function such that this points to o, resulting in a display of "CSS".