loading...
Cover image for this Keyword in JavaScript

this Keyword in JavaScript

bhagatparwinder profile image Parwinder 👨🏻‍💻 ・2 min read

JavaScript with Parwinder (40 Part Series)

1) What is Javascript? 2) Where can I run JavaScript? 3 ... 38 3) Types in JavaScript 4) What are objects in JavaScript? 5) Reference vs Value 6) Arrays in JavaScript 7) Array Methods in JS 8) Array Instance Methods 9) Array Instance Methods II 10) Functions in JavaScript 11) Type of Functions in JavaScript 12) Scope in JavaScript 13) Hoisting in JavaScript 14) Closures in JavaScript 15) Debugging in JavaScript: Console Methods 16) The new Keyword in JavaScript 17) JavaScript: Type Conversion 18) JavaScript: While Loop 19) JavaScript: Do While Loop 20) JavaScript: For Loop 21) Lesser-Known JavaScript Tricks 22) Events & Event Handling 23) Event Bubbling 24) Event Capturing 25) JS: Switch Statement Explained 26) Arrow Function: Basics 27) this Keyword in JavaScript 28) Arrow functions & this keyword 29) Callback Functions & Callback Hell 30) Strict Mode in JavaScript 31) Optional Chaining 32) Timers & Intervals 33) Arrow Function and The new, arguments & super Keyword! 34) Promises: Introduction 35) Promises: Chaining, Error Handling & Operators 36) New Promise Methods: allSettled & any 37) Async/Await: Introduction 38) Async/Await: Common Mistakes 39) Async/Await: Error Handling 40) Truly Understand Bind, Call & Apply

this keyword and functions

The this keyword in JavaScript is a property of an execution context, whether it is global, function, or eval. For regular JavaScript functions, this could change based upon how they were called.

  1. By itself, this refers to the global object.
  2. The new object, when used in a constructor.
  3. The base object, when the function enclosing, was called as a method of the object.
  4. undefined in case of strict mode.
  5. In an event, this refers to the element that received the event.

We have used this behavior for so long that most JavaScript developers are used to it. Let's go over some examples:

By itself, this refers to the global object.

function foo() {
    return this;
};

console.log(foo()); // window object in a browser, global object for node execution

The new object, when used in a constructor.

function Order(main, side, dessert) {
    this.main = main;
    this.side = side;
    this.dessert = dessert;
    this.order = function () {
        return `I will have ${this.main} with ${this.side} and finish off with a ${this.dessert}`;
    }
}
const newOrder = new Order("sushi", "soup", "yogurt");

console.log(newOrder.order());
// I will have sushi with soup and finish off with a yogurt

The base object, when the function enclosing, was called as a method of the object

const myObject = {
    main: "butter chicken",
    side: "rice",
    dessert: "ice cream",
    order: function () {
        return `I will have ${this.main} with ${this.side} and finish off with ${this.dessert}`;
    }
}

console.log(myObject.order());
// I will have butter chicken with rice and finish off with ice cream

In the above example, this refers to myObject, and it can access the properties of the object.

undefined in case of strict mode

"use strict";
function foo() {
    return this;
};

console.log(foo() === undefined); // true

In an event, this refers to the element that received the event.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta content="text/html;charset=utf-8" http-equiv="Content-Type">
    <meta content="utf-8" http-equiv="encoding">
</head>
<body>
    <button id="mybutton">
        Click me!
    </button>
    <script>
        var element = document.querySelector("#mybutton");
        element.addEventListener('click', function (event) {
            console.log(this); // Refers to the button clicked
            console.log(this.id); // mybutton
        }, false);
    </script>
</body>
</html>

We discussed arrow functions in the previous blog post and this keyword in the current one. The next blog post will combine arrow functions with this keyword to showcase how arrow functions behave differently than standard function expressions.

JavaScript with Parwinder (40 Part Series)

1) What is Javascript? 2) Where can I run JavaScript? 3 ... 38 3) Types in JavaScript 4) What are objects in JavaScript? 5) Reference vs Value 6) Arrays in JavaScript 7) Array Methods in JS 8) Array Instance Methods 9) Array Instance Methods II 10) Functions in JavaScript 11) Type of Functions in JavaScript 12) Scope in JavaScript 13) Hoisting in JavaScript 14) Closures in JavaScript 15) Debugging in JavaScript: Console Methods 16) The new Keyword in JavaScript 17) JavaScript: Type Conversion 18) JavaScript: While Loop 19) JavaScript: Do While Loop 20) JavaScript: For Loop 21) Lesser-Known JavaScript Tricks 22) Events & Event Handling 23) Event Bubbling 24) Event Capturing 25) JS: Switch Statement Explained 26) Arrow Function: Basics 27) this Keyword in JavaScript 28) Arrow functions & this keyword 29) Callback Functions & Callback Hell 30) Strict Mode in JavaScript 31) Optional Chaining 32) Timers & Intervals 33) Arrow Function and The new, arguments & super Keyword! 34) Promises: Introduction 35) Promises: Chaining, Error Handling & Operators 36) New Promise Methods: allSettled & any 37) Async/Await: Introduction 38) Async/Await: Common Mistakes 39) Async/Await: Error Handling 40) Truly Understand Bind, Call & Apply

Posted on by:

bhagatparwinder profile

Parwinder 👨🏻‍💻

@bhagatparwinder

Happy, cheerful, confident. Web developer based out of Chicago :)

Discussion

markdown guide