JS Famous "this" keyword Home


=> A function's this keyword behaves a little differently in JavaScript compared to other languages.
It also has some differences between strict mode and non-strict mode

In most cases, the value of this is determined by how a function is called (runtime binding). It can't be set by assignment during execution, and it may be different each time the function is called. The Function.prototype.bind() method can set the value of a function's this regardless of how it's called, and arrow functions don't provide their own this binding (it retains the this value of the enclosing lexical context).


Global Context

=> In the global context (outside of any function), this refers to global object whether in strict mode or not.
console.log(this === window); // true

Function Context

=> the value of this depend on how the function is called.
=> In non-strict mode, the value of this will be global object (window object in browser) because it is not set by the call.

						
							function foo() {
								console.log(this === window);	// true	
							}
							foo();
						 
						

=> In strict mode, however, if the value of this is not set when entiring an execution context, it remains as undefined
						
							function foo() {
								console.log(this === window);	// false	
							}
							foo();
						 
						


this can't be assigned during execution, throws SyntaxError
> this = 123; // Left side of assignment is not a reference.


3 ways to invoke function in JS

1. functionName();
2. functionName.call();
3. functionName.apply();


Example
					
						function foo(arg1, arg2) {
							console.log("this =>", this);
							console.log(arg1, arg2);
						}

						foo('a', 'b');
						// this => Window {...}
						// a b

						foo.call('Hello', 1, 2);
						// this => String {'Hello'}
						// 1 2

						foo.apply({x:1, y:2}, ['a', 'b']);
						// this => {x:1, y:2}
						// a b

						foo.bind(12)(22, 33); // binds argument to this and returns a function, so need to call with func arg
						// this => Number {12}
						// 22 33
					
				

arrow function

=> arrow function doesnot have its this value.
=> arrow function doesnot have its arguments parameter.


Example

						const func = () => {
							console.log(this); // Window {...} because the outer surrounding value of 'this' is window object
						}
						func();
					
						const func = () => {
							console.log(arguments); // Uncaught ReferenceError: arguments is not defined
						}
						func();
					
this, arguments value inside arrow function is same as of its outer scope.
In non-strict mode
						function outer() {
							console.log(this); // Window object
							const func = () => {
								console.log(this); // Window object
							}
						}
						outer();
					

In strict mode
						"use strict";
						function outer() {
							console.log(this); // undefined
							console.log(arguments); // Arguments(3) [1, 2, 3]
							const func = () => {
								console.log(this); // undefined
								console.log(arguments); // Arguments(3) [1, 2, 3]
							}
							func(6, 7, 8);
						}
						outer(1, 2, 3);
					


Function Binding

When passing object method as a callbacks, for instance to setTimeout there's a known problem: "losing this"

Solution:
1. Wrapper
2. bind
3. call + Wrapper
4. apply + Wrapper

Problem losing this Example:

						
							const user = {
								firstname: "Tina",
								lastname: "Xing",
								getFullName: function() {
									console.log(this);
									console.log(`${this.firstname} ${this.lastname}`);
								}
							}
							setTimeout(user.getFullName, 2000);
							// OUTPUT
							// Window object
							// undefined undefined

						
					
Explanation: setTimeout is a function inside window object, so this value is window object and
window object doesnot have variable firstname, lastname hence undefined.

In javascript, function is an object that is stored in heap memory with a refrence pointing to it. So, when we pass function refrence (in our case 'user.getFullName' in setTimeout) it will directly point to the function object in heap memory not through the 'user' object so 'user' this is lost and setTimeout is called with the window object so this is window object now.

1. Wrapper

						
							setTimeout(() => user.getFullName(), 2000);
							// OUTPUT
							// user object
							// Tina Xing
						
					
setTimeout will execute callback function after 2 sec and the statement inside this function.

2. Bind
						
							setTimeout(user.getFullName.bind(user), 3000);
							// OUTPUT
							// user object
							// Tina Xing
						
					

3. Wrapper + call
						
							setTimeout(() => user.getFullName.call(user), 4000);
							// OUTPUT
							// user object
							// Tina Xing
						
					

4. Wrapper + apply
						
							setTimeout(() => user.getFullName.apply(user), 5000);
							// OUTPUT
							// user object
							// Tina Xing
						
					


When to use arrow function

=> More suitable for non-method function.

						Problem:
						
							const user = {
								firstname: "Tina",
								lastname: "Xing",
								arrowFunc: () => {
									console.log(`${this.firstname} ${this.lastname}`);
								}
							}

							user.arrowFunc(); // arrow function doesnot have its own this keyword
							// OUTPUT
							// undefined undefined
						
					

Note: Use arrow function when you do not need to use this keyword related to object.

Use Case

					
						const user = {
							firstname: "Tina",
							languages: ['javaSE', 'javaEE', 'SpringCore', 'SpringSecurity', 'javascript', 'React', 'NodeJS', 'Angular'],
							printLanguages: function() {
								console.log(this); // user object
								this.languages.forEach(function(lang) {
									console.log(this);	// window object
									console.log(`Miss ${this.firstname} teach ${lang}`);
								})
							}
						}
						user.printLanguages();
						// OUTPUT
						// Miss undefined teach javaSE (so on  'this.firstname' is undefined)
						// because function(lang){ ... } is not called by programmer code instead its get called by window object 

					
				
Solution would be to use arrow function
					
						const user = {
							firstname: "Tina",
							languages: ['javaSE', 'javaEE', 'SpringCore', 'SpringSecurity', 'javascript', 'React', 'NodeJS', 'Angular'],
							printLanguages: function() {
								console.log(this); // user object
								this.languages.forEach((lang) => {
									console.log(this);	// user object
									console.log(`Miss ${this.firstname} teach ${lang}`);
								})
							}
						}
						user.printLanguages();
						// OUTPUT
						// Miss Tina teach javaSE 
						// Miss Tina teach javaEE 
						// and so on...