The this keyword in JavaScript has often been a source of much confusion for beginners to the language. Some of this confusion stems from the fact that this in JavaScript is treated differently as compared to in other languages like in Java or self in Python. this and Functions Functions, in JavaScript, are essentially objects. Like objects they can be assigned to variables, passed to other functions and returned from functions. And much like
objects, they have their own properties. One of these properties is this. this with function invocation:Function invocation refers to the process of invoking a function using its name or an expression that evaluates to the function object followed by a set of opening and closing first brackets(inclusion of the brackets indicates that we are asking the JavaScript engine to execute the function immediately). JavaScript
this inside the doSomething function, if it is invoked through the function invocation as above, has the value of the global object, which is the window object in the browser environment: JavaScript
Output: test value However, this is not always the case. If the doSomething() function were running in strict mode, it would log undefined instead of the global window object.This is because, in strict mode(indicated by the
line : ‘use strict’;), the default value of this, for any function object is set to undefined instead of the global object. JavaScript
Output: undefined undefined this with method invocation:Functions, when defined as fields or properties of objects, are referred to as methods. JavaScript
Output: John is 31 years old In the above code example, logInfo() is a method of the person object and we invoked it using the object invocation pattern. JavaScript
Output: [object Object] 1 [object Object] 2 In the above example, calc() is a method of the add object and is therefore called using the method invocation rules in lines 9 and 10. JavaScript
Output: [object Object] [object Window] NaN [object Object] [object Window] NaN Let’s try to understand what just happened. JavaScript
Output: [object Object] [object Object] 1 [object Object] [object Object] 2 Other solutions to this problem involve using bind(), call() or apply(), which we will soon look into. this with constructor invocation:Constructor
invocation is performed when new keyword is followed by an function name, and a set of opening and closing parentheses(with or without arguments). JavaScript
Output: John is 21 years old
Supported Browser:
|