The usage of Arrow Functions within Object Literal Syntax

I can't seem to understand why an arrow function within an object literal is invoked with window as the context for this. Any insights on this would be greatly appreciated.

var arrowObject = {
  name: 'arrowObject',
  printName: () => {
    console.log(this);
  }
};

// Outputs: Window {external: Object, chrome: Object ...}
arrowObject.printName();

On the other hand, here's an object that behaves as expected:

var functionObject = {
  name: 'functionObject',
  printName: function() {
    console.log(this);
  }
};

// Outputs: Object {name: "functionObject"}
functionObject.printName();

As per observations in the Babel REPL, it appears they are transpiled like so:

var arrowObject = {
  name: 'arrowObject',
  printName: function printName() {
    console.log(undefined);
  }
};

This contrasts with:

var functionObject = {
  name: 'functionObject',
  printName: function printName() {
    console.log(this);
  }
};

The question remains: Why does arrowObject.printName(); not have arrowObject as the value of this?

Logs were generated using Fiddle (with no use strict; directive).

Answer №1

Remember that the Babel translation assumes strict mode, while the use of window in your code indicates that you are running it in loose mode. If you switch Babel to assume loose mode, the transpilation will be differently:

var _this = this;                    // **

var arrowObject = {
  name: 'arrowObject',
  printName: function printName() {
    console.log(_this);              // **
  }
};

Take note of the _this global and console.log(_this);, as opposed to console.log(undefined); in the strict-mode transpilation of your code.

I'm trying to understand why an arrow function within an object literal has window as its this.

This happens because arrow functions inherit their this value from the context in which they are created. When you do this:

var arrowObject = {
  name: 'arrowObject',
  printName: () => {
    console.log(this);
  }
};

...the value of this is window. (This implies that you are not using strict mode; I suggest using it unless there is a specific reason not to.) If it were something else, such as the undefined value in the global strict mode context, then this within the arrow function would instead refer to that value.

The context in which the arrow function is created may become clearer if we break down your initializer into its equivalent logical form:

var arrowObject = {};
arrowObject.name = 'arrowObject';
arrowObject.printName = () => {
  console.log(this);
};

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

What could be causing the presence of additional characters in the responseText received from the Servlet to JavaScript via Ajax?

I am currently involved in a project where I am attempting to retrieve the username from a session that was created using the code below: GetCurrentUserInfo.java package servlet; import java.io.IOException; import java.io.ObjectOutputStream; import java ...

Standardize API data for utilization in Redux

I have an API that provides the following data: const data = { id: 1, name: 'myboard', columns: [ { id: 1, name: 'col1', cards: [ { id: 1, name: 'card1' }, { id: 2, name: 'card ...

What is the reason behind the non-exportation of actions in Redux Toolkit for ReactJS?

Currently, I am utilizing @reduxjs/toolkit along with reactjs to create a shopping cart feature. However, I am encountering an issue when attempting to export actions from Cart.js and import them into other files like cart.jsx and header.jsx. The error mes ...

Does each imported module in a Next.js app run multiple times?

There is a common understanding that when a module is imported multiple times within a JavaScript program, it only executes once during the first import. Informative article: The concept is straightforward: each module is evaluated just once, meaning th ...

Endless AngularJS loop using ng-view

I recently started experimenting with AngularJS for a new project I am working on, but I have encountered a problem when dealing with routes and views. For the sake of simplicity, I have minimized this example to its basic form, yet the issue persists. Th ...

What causes certain files to sporadically duplicate themselves in Visual Studio Code?

While using vscode for NodeJS development, I have noticed that certain files seem to duplicate themselves sporadically. Why is this happening and what steps can I take to resolve it? I am unsure of how to tackle this issue... ...

Navigating through drop-down menus using jQuery

I need help with a JavaScript script that can calculate the total number of points based on selected checkboxes and dropdown values. Currently, my script is able to iterate through checkboxes and assign 1 or 2 points based on their classes, but I'm st ...

React/Javascript - Executing Function returns prematurely

I have been working on a function that takes an object and iterates through it to create a search query. However, the issue I'm facing is that the function returns before I finish looping through the object: export default function buildQuery(query) ...

Collaborative session sharing between two node applications through Single Sign-On (SSO

I currently have a website created with express and node.js. I need to add a nodebb forum to this website, which is a separate node application. Both the main site and the forum use Facebook login, but users have to log in separately using the same Faceboo ...

Saving form data with a tinymce textarea, radio button, and checkbox to the database

My form contains multiple textarea fields, radio buttons, checkboxes, and a select input. Initially, I was able to submit the form using PHP without any issues. However, when I integrated TinyMCE with one of the textareas, I had to introduce JavaScript to ...

Unable to locate additional elements following javascript append utilizing Chrome WebDriver

I have a simple HTML code generated from a C# dotnet core ASP application. I am working on a webdriver test to count the number of input boxes inside the colorList div. Initially, the count is two which is correct, but when I click the button labeled "+", ...

How to position an absolute element beneath a fixed element

My website is experiencing a problem where the fixed header is overlapping an absolute paragraph on this page. Does anyone know how to resolve this issue? ...

Bringing the Jquery cursor into focus following the addition of an emoji

Looking to add emojis in a contenteditable div but facing an issue with the cursor placement. Here is a DEMO created on codepen.io. The demo includes a tree emoji example where clicking on the emoji adds it to the #text contenteditable div. However, after ...

What is the best way to display data in a React application depending on a boolean value?

Being new to React and JavaScript, I am currently struggling with boolean logic. I have a function called Profile which includes two constant methods that each return different data. function Profile(props) { const returnNormalProfile() const return ...

Transfer the data in the columns of Sheet1 to Sheet2 and eliminate any duplicates using Google App Script

Is there a way to transfer only unique rows from a SOURCE Spreadsheet to a DESTINATION spreadsheet? Spreadsheet #1 (SOURCE) - This sheet contains ID's and Names, but has duplicate rows. There are over 500k rows in this sheet and it is view-only. Spre ...

Trigger a popup notification with JavaScript when

Check out this snippet of code: <link rel="stylesheet" href="https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css"> <script src="https://code.jquery.com/jquery-1.12.4.js"></script> <script src="https://code.jquery.com/ui/ ...

What is the method for retrieving the IDs of checkboxes that have been selected?

I attempted running the following code snippet: <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <script type="text/javascript" src="http://static.jstree.com/v.1. ...

Accessing React Context globally using the useContext hook

I'm feeling a bit puzzled about how the useContext hook is intended to function in a "global" state context. Let's take a look at my App.js: import React from 'react'; import Login from './Components/auth/Login'; import &apos ...

I am encountering an issue with my authentication system where it is returning

I'm currently experiencing an issue with my authentication system using passport. For some reason, I keep getting an 'undefined' value returned. Can anyone provide assistance? Here is the code snippet in question: app.js passport.use(new L ...

Technique for updating URL when submitting a form on a webpage

I'm a newcomer to the world of coding and I have a simple issue that needs fixing. I want to create a form field where users can input the last segment of a URL provided to them. After entering this segment, I want the page to refresh automatically a ...