Can the function fn passed to setTimeout be called not as a function, but as a method like window.fn()?

When in strict mode, the value of this should be undefined inside a non-method (a function):

To see an example where this is undefined, visit http://jsfiddle.net/jfp06nc9/1/

However, if the setTimeout function is used, then this becomes bound to window:

Check out examples at http://jsfiddle.net/jfp06nc9/2/ and http://jsfiddle.net/jfp06nc9/3/. In these cases, this === window returns true.

It appears that the function fn passed to setTimeout is executed as a method rather than a function, like window.fn() or fn.call(window).

Take a look at http://jsfiddle.net/jfp06nc9/4/ for more examples showing this === window as true.

Is this really true? If you have insights from any specification, please share them in your response.

(Note: The jsfiddle test was conducted on Chrome 46.0.)

P.S. This question does not revolve around what this actually refers to; it is about how setTimeout behaves differently in non-strict and strict modes when running fn().

For reference, here is the setTimeout code snippet:

http://jsfiddle.net/jfp06nc9/7/

(function() {
    "use strict";
    setTimeout(function() {
        "use strict";
        console.log(this); 
    }, 1000);
}());

Given that the function runs in strict mode, the expectation is that if it is executed as a function, then this should be undefined. However, it evaluates to window

Answer №1

setTimeout is actually specified in the HTML standard (not ECMAScript), and it explicitly states that window should be utilized for this.

You can find the relevant section of the specification at this link

  1. If the method context is a WorkerGlobalScope object, let method context proxy be method context, otherwise utilize the corresponding WindowProxy for method context.

(emphasis added)

In addition:

4.2 Perform the appropriate steps from the following list:

If the first argument of the method is a Function

Invoke the Function. Use the third and subsequent arguments of the method (if any) as input for invoking the Function. Utilize method context proxy as the thisArg when invoking the Function.

(emphasis added)

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

Having issues with modals in Angular 4 where HTML is not fetching the JS file

As I work on a gallery website for a photographer, I have encountered an issue with the functionality of the gallery itself. The main objective is to allow users to click on an image and open a modal where they can navigate through all the pictures in the ...

What is the best way to add extra plugins to a library that has already been imported through JSPM?

After successfully importing a 3D rendering library with JSPM, I encountered an issue while trying to import the Orbit Controls plugin for Three.js import THREE from 'three.js/build/three'; import OrbitControls from 'three.js/examples/js/ ...

Determine if a link can be activated or disabled

Controlling the clickability of a link and displaying an error based on the result of an ajax call is my current objective. <a class="lnkCustomer" href="http://localhost/viewcustomer" target="_blank" data-customerno="2 ...

What is the best way to handle POST parameters in express.js?

I'm trying to figure out how to retrieve an array containing all parameters sent in an HTTP request. After consulting the documentation at http://expressjs.com/4x/api.html#req.params I understand that using req.params and req.query, params will refe ...

What is the best location to store the JWT bearer token?

Exploring options for storing JWT tokens in a Bearer header token for my application. Looking for the most efficient storage mechanism. Would love some insight on how to accomplish this using jQuery. Any recommendations for a secure method? ...

Determining if a URL links to an image when the file extension is not informative

I am currently working on building an AJAX call to retrieve data from an API with a messy data structure. The challenge I'm facing is that the array returned by each AJAX call can contain up to 30 elements, some of which have image URLs without a file ...

Utilizing Ajax to Transmit Particular Information on Partials in Rails

Exploring the realm of rails, I am embarking on a quest to achieve the following: The mission at hand involves crafting a store and unstore button to save and 'un-save' events respectively. My strategy includes leveraging event attributes and cu ...

Guide for invoking a servlet via a navigation bar hyperlink and implementing a jQuery feature for smooth scrolling upon clicking

Is there a way to call a servlet from a navigation bar href link and at the same time trigger a jQuery function for smooth scrolling down? I attempted to call the servlet using an onclick href link, it successfully calls the servlet but does not trigger t ...

Using optional chaining along with the methods toLowerCase and indexOf while iterating through an array using the map

I have implemented an autocomplete input that searches for project properties while typing. I am looking to enhance the existing code for better performance. filterProjects(value: string) { return this.projects.filter( project => project.key ...

What is the process for adding submitted data to an already-existing local JSON file?

I have a new Angular assignment that requires me to push form data into an existing JSON file locally. The task is to develop an Angular application where users can create new tasks and view them on a separate page. Initially, I attempted using http.post ...

DiscordJS: updating specific segment of JSON object

I am currently working on a Discord bot using discord.JS that involves creating a JSON database with specific values. I'm wondering how I can modify the code to edit a particular object within the JSON instead of completely replacing it. if (message.c ...

The left side of the page is anchored with text content while an engaging carousel occupies the right half

Looking to create a section on the website that remains fixed while a carousel scrolls vertically. Once you reach the final slide, scrolling will continue on the page rather than changing the carousel slide. Want it to function similarly to the Creative s ...

Looking to modify the CSS of an element during a drop event using interact.js?

I've encountered an issue in my code where setAttribute and .transform are not working as expected. I have tried using them within the ondrop event function, but with no success. interact('.dropzone') .dropzone({ // Setting the r ...

Angular watch triggering even when the old and new values remain unchanged

function displayController($scope) { $scope.currentView = myCustomInstance.currentView; $scope.$watch($scope.currentView, function(newValue, oldValue) { console.log(newValue); cons ...

The sluggish loading speed of the page is being caused by both jQuery and an external file containing Amazon

I am facing an issue with my website where it is loading over 1000 images per page from Amazon servers. To enhance the functionality, I have integrated jQuery plugins that are stored locally on the webserver, without using any remote JS or CSS. However, ...

Issue with mobile.changePage() function not executing as expected

I created a basic code that generates a "Splash screen". For storing my data, I am utilizing localstorage. When I first load it, I retrieve data from a URL and I am able to navigate to different pages using $.mobile.changePage(). However, if the data is a ...

How can I trigger a function after all nested subscriptions are completed in typescript/rxjs?

So I need to create a new user and then create two different entities upon success. The process looks like this. this.userRepository.saveAsNew(user).subscribe((user: User) => { user.addEntity1(Entity1).subscribe((entity1: EntityClass) => {}, ...

Can we save javascript-generated HTML audio as a file on the back-end server?

In my latest project, I am building a JavaScript sequencer that controls HTML audio using intervals and timeouts. The goal is to handle all the processing and recording on the back-end while displaying a "Processing..." message to the user, and then utili ...

jQuery Ajax handles only single form submissions effectively

I am diving into the world of jQuery and Ajax for the first time, testing my skills by creating a form with new features that challenge me. This simple form collects name, last name, email, and phone number. Initially, everything functions smoothly - form ...

Express.js enables dynamic routing by leveraging request parameters

Currently, I am in the process of developing a RESTful API with expressJS. Within my controller, I have multiple functions such as Chall_1, Chall_2, and so on. exports.validateChall_1 = function(res) { //logic res.json(1); }; exports.validateChall_2 = f ...