What causes the variation in `this` when viewing index.html in a browser versus supplying index.html through a node server?

My html file named index.html is referencing a javascript file

<!DOCTYPE html>
<html lang="en">

<head>
    <title>asd</title>
    <meta charset="utf-8">
</head>

<body>
    <div id="app"></div>
    <script src="index.js"></script>
</body>

</html>

The contents of my index.js

function init() {
    // always prints the window-object
    console.log("init this:", this);
}
var testFunc = () => {
    // this = {} when served
    // this = window when opened directly in browser
    console.log("testFunc this:", this);
}
// prints the window-object when opening index.html
// prints {} when using a server
console.log("this:", this);
init();
testFunc();

I am puzzled by the fact that when I open the index.html file directly in the browser (url: file:///index.html), it always sets this to be the window-object, but when I serve the index.html file with a server (url: http://localhost:1234/), sometimes {} is printed and other times window.

I initially anticipated getting {} when executing testFunc(), and having window as the output in all other cases. Why is there such inconsistency?

Just for reference: I utilized parcel to serve my application.

Answer №1

console.log("this:", this);

this, when used in a global context, points to the global object.

init();

Without a set value for this and not in strict mode, within the init function it will reference the global object (if in strict mode, it would be undefined).

testFunc();

As testFunc is an arrow function, its this is taken from its surrounding scope, which in this case is the global object once again.

In web browsers, the window object serves as an alias for the global object and contains extra properties like escape and unescape, while also implementing the window interface.

The way an object is displayed in the console can vary depending on the console's implementation.

Answer №3

This refers to the global object within the specific environment where the code is running, which explains why it may vary each time.

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

Delete the entry with the specified unique identifier "this text" from the MongoDB database

So, I've been searching high and low but still can't seem to figure out how to get this to work. Here's the issue I'm facing: I'm currently working on a chat application using node/express/socketio, and I'm attempting to crea ...

The cookie being sent from the backend API (implemented in nodeJS using express) to the frontend (developed with NextJS) is not successfully setting in the

I'm currently working on a NextJS app running on localhost:3000 and a node express API running on localhost:3030. I have encountered an issue where, after sending a request from the frontend to the backend login route, I am trying to set a cookie call ...

Attempting to create an array using jQuery's :checked selector

In my table structure below, I have multiple rows with various data: <tr class="row"> <td class="row-checkbox-delete-row"> <input tabindex="-1" class="checkbox-delete-row" type="checkbox" /> </td> <td class="r ...

Issues arise with selecting text and highlighting it in JavaScript functions

I am currently working on a fun little web application that allows users to select text and highlight it in any color they choose. Here is the progress I have made so far: function replaceSelectedText() { var sel, range; var replacementText, spanT ...

Different Methods for Iterating through Data when Formatting for D3.js

Struggling with an error previously discussed on StackOverflow. The issue lies in my D3.js code struggling to iterate through an object. Raw data is sourced from a RESTful web api, loaded into a variable 'dataset' using jQuery and JavaScript. Out ...

JSON error: Encountered an unexpected token "o" while processing

My database table: TABLE `events` ( `event_id` INT(11) unsigned NOT NULL AUTO_INCREMENT, `event_title` VARCHAR(255) NOT NULL, `event_desc` TEXT, `event_location` VARCHAR(255) NOT NULL, `event_requirements` TEXT DEFAULT NULL, `event ...

Characteristics of JSON data containing quotation marks within the property values

Is it possible to include JavaScript functions in JSON like the example below? My JSON library is struggling to process this structure because of the quotations. How can I address this issue? I specifically need to store JavaScript functions within my JSON ...

Using jQuery to target the td:nth-child selector inside a document.ready function is not viable

Currently, I am working on a language learning project where I import a table of German words and their English translations from a .csv file using the jQuery.csvToTable plugin. My goal is to replace the words in the cells with an HTML input when the lang ...

Unique custom CSS and meta tag options for enhancing iPad/iPhone user experience

Currently, I am developing a web application that integrates Extjs components, PHP, and MySQL. My main goal is to ensure that my application looks correct on the iPad. Are there any specific CSS rules or meta tags that I should be implementing for optima ...

Authenticate yourself as a user or an organization on mongodb

I am currently developing an application that requires user registration and login, as well as organization registration and login. I have implemented the use of Node.js Passport with a local strategy for authentication. While I have successfully created t ...

What is the most effective method to exhibit every element within a content wrapper at a specific interval of time?

I am looking for a way to display each div within the content-wrapper after a specific time interval. Currently, I am using individual classes like el1, el2, el3, ... to accomplish this task. However, when dealing with content-wrappers containing multipl ...

What is the process for transferring items using ref ObjectId's?

https://i.sstatic.net/pi6js.pngI'm currently in the process of developing a small personal betting website. I have successfully created Arrays of ObjectId's within each collection that reference one another. However, I am facing challenges when i ...

What could be causing the unexpected behavior of TypeScript in Visual Studio Code?

VSCode is showing errors, but everything is functioning properly. Here are some of the errors: Type expected. [ { "resource": "/C:/Users/Dell/Desktop/vite-project/src/App.tsx", "owner": "typescript", "code": "1110", "se ...

Leverage the version attribute within package.json within one of its scripts

Is there a way to access the version attribute of my package.json file within one of its scripts? I want to include the version number in the name of the JS bundle, instead of using a hash as an identifier. This is what I currently have: "build-js": "bro ...

Graph columns failing to display on Chart.js bar chart

I'm currently facing a challenge while trying to create a bar chart using HTML and JavaScript. Unfortunately, the bars are not showing up for some reason. I have included the code snippet below along with an imagehttps://i.stack.imgur.com/4H7ol.png. ...

What is the best way to retrieve a variable from MySQL in a Node.js environment?

var result; function getName(id) { //Retrieve name from database connection.query(`SELECT name FROM users WHERE id = "${id}"`, function (err, rows, fields) { if (err) console.log(err); result = rows[0].name; }); console.lo ...

Managing browser closure (x) using JavaScript or jQuery

Is there a way to handle browser close (by clicking the cross on the top right side) using javascript or Jquery without triggering events whenever the page is refreshed, navigated back and forth in the browser? I have seen many forums and blogs suggesting ...

What is the reason for using a string as the index of an array in the following code?

var arrayOfNumbers = [1, 2, 3, 4, 5, 6, 78]; for(var index in arrayOfNumbers){ console.log(index+1); } The result produced by the given code snippet is as follows: 01 11 21 31 41 51 61 What is the reason behind JavaScript treating these ...

Error: The strategy for authentication is not recognized as "login" - Express and Passport

I am currently experimenting with a basic MEAN stack tutorial I found online. The technologies involved are: Node.js Express.js Passport.js Below is the code snippet for the application file: app.js var express = require("express"); var mongoose = req ...

Save all dynamically received data from a form in PHP as an array

I have developed a PHP form that dynamically adds new text variables in this manner: <form action="" enctype=”multipart/form-data” method="post" action="<?php echo $_SERVER['REQUEST_URI'];?>"> <div id="div"> va ...