Kaptan Bhardwaj :
As we can assign a function call to a new reference in javascript for example we have a function display and when we call it we use display(). And we know in javascript we can also create a reference for this for example var call = display()
,So can i invoke this function using this call() reference ? below is my code it is not working it is showing outerDisplay is not a function why is this happening ?
<script>
var obj = {
name: 'Saurabh',
display: function () {
console.log(this.name); // 'this' points to obj
}
};
var outerDisplay = obj.display(); // Saurabh
outerDisplay();
</script>
bravemaster :
outerDisplay
is not a function because it already called obj.display(). However if you changed code like the below one, it won't work:
var outerDisplay = obj.display;
outerDisplay(); // it won't work!
Because it lost the "owner" of this function. You have to tell who is the owner with call
.
var obj = {
name: 'Saurabh',
display: function(){
console.log(this.name); // 'this' points to obj
}
};
var outerDisplay=obj.display; // Saurabh
outerDisplay.call(obj);
MDN web docs link: Function.prototype.call()