In JavaScript, ‘this’ behaves differently compared to other programming languages. If we are performing a normal function call then ‘this’ points to the window object. But we are calling the function differently than ‘this’ will point to a near object. To understand it better below we elaborated with two code snippets with two different call approaches.
Example 1: When we call a function in a normal way in the below example
Javascript
function printThis(){ console.log( this ); } printThis(); |
Output:
Window {0: Window, window: Window, self: Window, document: document, name: '', location: Location, …}
Example 2: When we call a function using object notation.
Javascript
var obj={ name: "Ramesh" , printThis: function (){ console.log( this ); } } obj.printThis(); |
Output:
{name: 'Ramesh', printThis: ƒ}
So, from the above two examples, we can clearly understand the behavior of ‘this’ when we make different types of function calls.
Approach: First create an object and enter sample properties. Make sure you add a function for one key, in that function add a callback function using setTimeout. Inside this setTimeout function use ‘bind’ to bind the context of this after then return this.
Example: Using Bind
Javascript
var outerFunction= function (){ innerFunction = function () { }; setTimeout(innerFunction.bind( this ),2000); return this ; }; var obj = { method: outerFunction ,company : 'neveropen' } ; obj.method(); |
Output: