The perplexing nature of the "this" keyword in JavaScript

Original Code - Version 1:

const myobj = {
    a1 : 10,
    b1 : 20,
    c1 : 30,

    myfunc1 :function() {

    console.log(this)
    
    const myfunc2  =  function ()     {
        let a2 =100
        console.log(this)
    }
        myfunc2()

    }

}



myobj.myfunc1()

Output:

{a1: 10, b1: 20, c1: 30, myfunc1: ƒ}
Window {window: Window, self: Window, document: document, name: '', location: Location, …}

Revised Code - Version 2:

const myobj = {
    a1 : 10,
    b1 : 20,
    c1 : 30,

    myfunc1 :function() {

    console.log(this)
    
    const myfunc2  =   () =>     {
       let a2 =100
        console.log(this)
    }
        myfunc2()

    }

}



myobj.myfunc1()

Output:

Object a1: 10 b1: 20 c1: 30 myfunc1: ƒ ()[[Prototype]]: Object
Object a1: 10 b1: 20 c1: 30 myfunc1: ƒ ()[[Prototype]]: Object

I am struggling to grasp the behavior of the 'this' keyword in JavaScript.

Issue Faced: In the first version of the code, when I use the 'this' keyword inside myfunc1, it refers to myobj. However, when I create another function like myfunc2 and call it within myfunc1, it references the window object. I am puzzled by this behavior, especially since the functions are created and called within the myobj object literal.

In the second version of the code, the 'this' keyword inside myfunc1 points to myobj, as expected. Additionally, when the arrow function myfunc2 is created inside myfunc1, it correctly references the myobj object literal because arrow functions capture the scope in which they are created.

My confusion lies in why, in the first version of the code, even though the functions are within the myobj literal, the 'this' keyword still references the window object.

Answer №1

In programming, the "this" keyword is used to point to the specific object that is currently running the code. It indicates the object executing the current function or method. When referring to a regular function, "this" points to the global object. However, when referencing a method within an object, "this" points back to the object itself.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

JavaScript Document Object Model: Locate an element with a class that is either similar to or includes a specific substring

I am facing a situation where I need to locate a wrapper element with a specific class name that includes a random id, such as wp-rgtayfu-fxyjzw-wrapper. The class will always have the substring wrapper in it, and there is only one element in the document ...

Modifying the HTML <select> element with JavaScript

[resolved] I'm encountering an issue with the code below that is supposed to dynamically change the options in a second drop-down menu based on the selection made in the first menu. I've tried to troubleshoot the problem but haven't been suc ...

What is the best way to implement an ng-change function on multiple fields within the same page without causing a cyclic call loop?

In my page, I have three angular-moment-datepicker fields - a date picker field, a month picker field, and a year picker field respectively. Here is the code: <input class="form-control" placeholder="BY DAY" ng-model="date" moment-picker="gDate" start- ...

Is there a way to display my array within my React component using JavaScript?

I am working with an element that looks like this: const DropdownElements = [ { key: 1, title: "City", placeholder: "Select City", apiUrl: "https://api.npoint.io/995de746afde6410e3bd", type: "city&qu ...

How to display a video with full height and width using CSS or JavaScript

I am trying to incorporate an html5 video (using the video tag) with 100% width and 100% height to play in the background. I have seen an example using an image, but I want to achieve the same effect with a video. Here is the code I have so far: #video { ...

Sending information to Bootstrap 4 modal

Can you help me insert the variable into this link? <a href="#edit_task" data-toggle="modal"><i class="fas fa-edit fa-lg fa-fw"></i></a> This is my modal: <div class="modal fade" id=" ...

Guide to utilizing Reduce for obtaining a fresh Array of Objects in Javascript

I am a beginner in coding, so I apologize if this question seems basic. I am working with an array that contains different types of pies along with their prices: pieArr = [blueberry, strawberry, pumpkin, apple] My goal is to create an array of objects re ...

The AJAX call fails to refresh the secondary table in CodeIgniter

I have a situation where I need to display data from two tables - car producer and car model, pulled from a database. My goal is to filter the second table to only show cars from a specific producer when that producer is clicked in the first table. I attem ...

"Interactive demonstration" image toggle through file upload

I have a project to create a "demo" website for a client who wants to showcase the template to their clients. A key feature they are interested in is allowing users to upload their logo (in jpg or png format) and see it replace the default logo image insta ...

When an iteration occurs within a for loop and a value changes, remember to incorporate a line break or equivalent element using jQuery

I am currently working on implementing a hierarchy system for users stored in a database table. At the moment, only top-level users with a hierarchy of 1 are displayed. When clicked, I use AJAX to retrieve and display all related users below them. These ...

How can the Node app utilize an HTML page to reference another JavaScript file? Ran into an unexpected syntax error: `Uncaught SyntaxError: Unexpected token '<

I'm trying to figure out how to call another script from an HTML page that is being served by my node project's localhost server. Here's the basic setup: index.js var http = require('http'); var fileSystem = require('fs' ...

Downloading files from a Blob in NodeJS: A step-by-step guide

How do I retrieve a file from a BLOB column using NodeJS? Currently, I am utilizing the oracledb library for database operations and my code snippet is as follows: async function getFile(req, res) { let filename = req.params.filename; let file = a ...

The fetch API does not retain PHP session variables when fetching data

After setting session variables in one php file, I am attempting to access those values in another php file. session_start(); $_SESSION['user'] = $row['user']; $_SESSION['role'] = $row['role']; However, when ...

The Npm generate script is failing to create the necessary routes

I've integrated vue-router into my nuxt project, but I encountered an issue when running npm run generate - it generates everything except for my pages. I suspect the problem lies with the router implementation as I didn't face any issues before ...

Tips for dynamically creating column headings and table values using JSON arrays in AngularJS

On a web page, there are two radio buttons that produce different results: The first button shows Student Details and the corresponding JSON array is as follows : [{"Name":"A", "Class":"x", "Section":"abcd", "DOB": "XYZ"}, {"Name":"B", "Class":"x", "S ...

How can we manually trigger $(document).ready() from within the ready callback of head.js using jQuery?

I am in search of ways to enhance the loading speed of a web application, particularly one that encompasses numerous javascript files on every HTML page. My plan is to experiment with head.js on a specific page to observe if it has a positive impact on loa ...

Personalized customizable elements in Draft.js (extension)

For instance, I am interested in enabling users to incorporate a dynamic slideshow of images into their page using Draft.js. This would allow them to select a predefined slideshow from my app and have it automatically update on their page if the images a ...

Having trouble obtaining search parameters in page.tsx with Next.js 13

Currently, I am in the process of developing a Next.js project with the Next 13 page router. I am facing an issue where I need to access the search parameters from the server component. export default async function Home({ params, searchParams, }: { ...

The route param is throwing a "Cannot read property 'name' of undefined" error, indicating that the property

Currently, I am enrolled in an ExpressJS course on TUTS+ From the video tutorial, I have implemented the following code snippet (excerpt from video): var express = require('express'), app = express(); app.get('/name/:name', funct ...

The carousel comes to a halt once it reaches the final slide and does not continue cycling

Currently working on a website project for a client and utilizing Bootstrap to create a carousel feature. I am specifically using Bootstrap 3.0. After searching for a similar issue here, I found two cases that resemble mine but unfortunately have no soluti ...