Assume that we have the following short JavaScript code:
<script> var number = 50; var obj = { number: 60, getNum: function () { var number = 70; return this.number; } }; alert(obj.getNum()); alert(obj.getNum.call()); alert(obj.getNum.call({number:20})); </script>
Will this code succeed or fail? and if it succeeds, what is the output of the alerts?
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
The code will work fine. The alerts will output 60
, 50
and 20
. Let’s understand why we will have these results.
The sequence of operations:
1. In obj.getNum()
, this.number
will return number
in obj
scope which is 60
.
2. In obj.getNum.call()
, this.number
will return number
in global scope because Function.prototype.call
‘s first parameter is not
specified which mean that the scope will be the global scope. So the result will be 50
.
3. In obj.getNum.call({number:20})
, this.number
will return number
in the object scope specified in the first parameter
of Function.prototype.call
method which is {number: 20}
. So the result will be 20
.
More information about Function.prototype.call() can be found here:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/call