What happens when you call array.map with 'this' as an argument?

Seeking to understand the binding of 'this' when a function is passed to the map method of an array.

Code snippet available on StackBlitz:

import './style.css';

class Foo {
  public method() { return this ? `"this" is a ${this.constructor.name}`
                                : '"this" is undefined'; }
}

class Caller {
  public method1(array) {
    return array.map(function() { return foo.method(); });
  }
  public method2(array) {
    return array.map(this.callMethod);
  }
  public method3(array) {
    return array.map(foo.method);
  }
  public method4(array) {
    return array.map(v => foo.method());
  }
  private callMethod() { return foo.method(); }
}

const foo = new Foo();
const caller = new Caller();
const array = [1];

document.getElementById('app').innerHTML = `
  <dl>
    <dt>Expected</dt>
    <dd>${foo.method()}</dd>
    <dt>Method 1 (anonymous function)</dt>
    <dd>${caller.method1(array)}</dd>
    <dt>Method 2 (class method)</dt>
    <dd>${caller.method2(array)}</dd>
    <dt>Method 3 (function reference)</dt>
    <dd>${caller.method3(array)}</dd>
    <dt>Method 4 (lambda function)</dt>
    <dd>${caller.method4(array)}</dd>
  </dl>
`;

The output reveals that most methods result in 'this' bound to the Foo object.

Confusion arises while referencing MDN's explanation of array.prototype.map, which states:

If a thisArg parameter is provided to map, it will be used as callback's this value. Otherwise, the value undefined will be used as its this value.

In none of the cases mentioned am I providing a thisArg parameter explicitly - so why do 3 out of 4 methods "work"?

Bonus question: oddly, commenting out the first line (import './style.css') enables method 3 to work correctly. Any insights?

Answer №1

Why do 3 out of the 4 methods work when the `thisArg` parameter is not explicitly provided in those cases mentioned above?

Even though the `thisArg` parameter is not passed to the `map` callback, it is important to note that the evaluation of `this` occurs within the context of a `Foo.method`, which is invoked in all three situations as:

foo.method()

This ensures that inside the `method`, `this` refers to `foo`. This behavior is not specific to `map` but rather reflects how calling a method with the dot operator behaves universally.

Bonus question: Why does commenting out the first line (`import './style.css'`) suddenly make method 3 work as well?

Contrary to what has been observed, removing the `import` statement results in the following output:

"this" is a Window

This outcome aligns with non-strict mode where `this` defaults to the global object if not explicitly defined within a function.

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

Ways to retrieve and bind data using onMounted in VueJS

Loading Data in Test.vue Component <template> <li v-for="item in masterCompany" v-bind:key="item.id"> {{ item.displayName }} </li> </template> <script> import Test from "../hooks/Test.hook" ...

The properties required for type 'never[]' are not present

The type 'never[]' does not have the necessary properties from type '{ login: string; id: number; node_id: string; avatar_url: string; url: string; }': login, id, node_id, avatar_url, url When working on a component that takes an ApiUr ...

What is the process to switch the div's contenteditable attribute value from "false" to "true"?

I am currently experimenting with angular2 and I have a need to alter the value of a div- I want to change all contenteditable="false" to contenteditable="true" on my HTML page. Note that at times the contenteditable="false" attribute may be added to a ...

Validation of passwords containing special characters in Angular2

I am working on setting up password validation requirements to ensure the field contains: Both uppercase letters, lowercase letters, numbers and special characters This is my current progress: passwordValueValidator(control) { if (control.value != u ...

Stopping HTTP client calls in OnDestroy hook of an Angular Service

Is it possible to automatically unsubscribe from an http call in an Angular service using the ngOnDestroy hook? Just to note, I am already familiar with using the rxjs 'take' operator or manually unsubscribing from the service within the compone ...

Changes in the styles of one component can impact the appearance of other

When it comes to styling my login page, I have specific stylesheets that I include in login.component.ts. For all the common CSS files, I have added them in the root index ("index.html") using the traditional method. However, after a user logs into the sys ...

In search of a particular class upon clicking

Two div containers are present: <!-- button1 --> <div class="voted"> <span>name</span> <div class="button">Vote</div> </div> <!-- button2 --> <div class="vote"> <span>name</span&g ...

typescript fetch and load JSON data from a URL into arrays

Currently, I am receiving JSON data from a URL. The data is structured in the following way: [ {"id":1,"symbol":"SP-500","date":"1927-12-30T07:00:00.000+00:00","open":17.66,"high":17.6 ...

Guide to iterating through a Cheerio element within an asynchronous function and updating an external variable

To develop an API that scrapes GitHub repositories for specific data, including file name, extension, size, and number of lines, I have decided to utilize Node with TypeScript. In order to streamline this process, I have created an interface called FileInt ...

Is there a way to prevent the URL of my Next.js app from constantly changing?

Our current Next.js project requires that the static URL remains constant, even when navigating between pages. This is a client requirement that we must adhere to. Can you provide suggestions on how we can achieve this? Maintaining the same URL throughout ...

Issue with Nestjs validate function in conjunction with JWT authentication

I am currently implementing jwt in nest by following this guide Everything seems to be working fine, except for the validate function in jwt.strategy.ts This is the code from my jwt.strategy.ts file: import { Injectable, UnauthorizedException } from &ap ...

What is the method for extracting date of birth data from .NET to Angular?

Struggling to fetch the date of birth from the database where it has been stored. After searching through multiple resources online, I am still unsure about how to accomplish this task. export class DetailsEmployeeComponent implements OnInit{ employeeD ...

Show a modal when the axios request is finished

EDIT: After some exploration, I've shared the solution I found in case it helps others facing a similar issue. I'm currently working on building a reusable Bootstrap 5 modal child component within Vue3. The goal is to pass an ID as a prop from t ...

Angular2 and TypeScript bug "The property METHOD_NAME is not found on the type 'typeof CLASS_NAME'"

Seeking assistance with Angular2 and TypeScript as I transition from A1 to A2. Currently, I am facing a situation that may seem obvious for experienced developers: Here's the scenario: Utilizing Webpack. AppConfigConst contains static, app-wide con ...

Custom-designed foundation UI element with a parameter triggers TypeScript issue

When running this tsx code: import React from "react"; import BaseButton from "@mui/base/Button"; import styled from "@emotion/styled"; export const enum BUTTON_TYPE { MAIN = "main", LINK = "link", } ...

Guide to automatically installing @types for all node modules

As a newcomer to Typescript and NodeJs, I have been experiencing errors when mentioning node modules in my package.json file and trying to import them. The error messages I always encounter are as follows: Could not find a declaration file for module &apos ...

Expanding the current module definition: A step-by-step guide

I have created a declaration file for an existing npm package, but it seems like one method was not declared. I attempted to add it, but encountered an error. Can someone please assist me? Here is the structure of the existing d.ts file: declare modul ...

Using functions like .map in a TypeScript model may not function properly

After retrieving data from a server, I created a TypeScript model to structure the incoming data as follows: export class DataModel{ public PageNo: number public showFromDate: string public showToDate: string public gradeFieldId: number } ...

Ways to resolve sonar problem "Ensure this function is updated or refactored to avoid duplicating the implementation on line xxx"

SonarQube has detected duplicate functions in specific lines: beneficiaires.forEach(beneficiaire => { () => { Below are the identified functions: affectPercentageToBeneficiares(beneficiaires: BeneficiaryData[], sum: number) { let numberOfBenefi ...

Encountered an error while attempting to compare 'true' within the ngDoCheck() function in Angular2

Getting Started Greetings! I am a novice in the world of Angular2, Typescript, and StackOverflow.com. I am facing an issue that I hope you can assist me with. I have successfully created a collapse animation for a button using ngOnChanges() when the butto ...