What exactly happens when function.prototype.apply is used with thisArg being included in the same array as the rest of the arguments?

For a date/temperature scatter plot, I needed to organize the data with a date-like string. Here is the structure I came up with:

var dateTemperatures = {
      '[2016,8,29]': {low: 63, high: 94},
      '[2016,9,2]': {low: 59, high: 81},
      '[2016,9,1]': {low: 58, high: 85}
  }

The purpose was to parse the keys using JSON.parse and extract the necessary details for creating a date object. I stumbled upon this Stackoverflow answer which demonstrated how to construct an object using both apply and new .... (). I applied this technique by substituting Something with Date:

var s = new (Function.prototype.bind.apply(Something, [null, a, b, c]));

This method worked effectively in a function I created to order the "Date" keys:

function orderTemperatureDates(dateTemperatures) {
      var orderedDates = [];

      for (var temperatureDate in dateTemperatures) {
          var YMD = JSON.parse(temperatureDate);
          YMD.unshift(null); //standard first argument to .apply()
          orderedDates.push(new (Function.prototype.bind.apply(Date, YMD)));
      }

      return orderedDates.sort(function(a,b){return a.getTime() - b.getTime()});
  }

Console output:

[Thu Sep 29 2016 00:00:00 GMT-0500 (Central Daylight Time), Sat Oct 01 2016 00:00:00 GMT-0500 (Central Daylight Time), Sun Oct 02 2016 00:00:00 GMT-0500 (Central Daylight Time)]

Regarding the example line from the mentioned Stackoverflow answer, there was confusion about how it works. According to the documentation, null can be the first argument followed by the remaining arguments passed separately. However, in the example and my code, null and the arguments are placed within the same array.

Answer №1

From what I understand, the first argument to apply can indeed be null, followed by the remaining arguments.

It is true that you are able to use null as the initial argument of apply in cases where you want the value of this inside the method to be set to null (or simply do not care about it). However, this scenario does not apply here.

In the expression

new (Function.prototype.bind.apply(Date, [null, 2016, 8, 29]))
, we do not provide null as the first argument for apply, as this is not our intention. We are utilizing the bind method and applying it to the Date object along with the subsequent arguments. This call can be equivalent to

new (Date.bind(null, 2016, 8, 29))

In this case, we pass null as the initial argument to bind because we are indifferent to the value which will be disregarded when the bound function is invoked with the new keyword.

Take a look at the following example:

function constructor(a, b, c) {
  "use strict";
  console.log(this, a, b, c);
}
var bound = constructor.bind(null, 1, 2, 3);
bound();
new bound();


If you are certain that YMD consists of exactly three elements, it would be simpler to write new Date(YMD[0], YMD[1], YMD[2]). In an ES6 context, you could also utilize spread syntax with new Date(...YMD) for the invocation.

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 is the best way to access the Node.js HelloWorld File that I created with a .js extension?

I am currently going through the materials at "NodeBeginner.org". Despite my limited experience with command line, I am struggling to execute my first file. The only success I've had so far is running "console.log('helloworld');" by typing ...

Capture a snapshot of a Bootstrap modal using JavaScript

var takeScreenShot = function(){ html2canvas(document.body, { onrendered: function(canvas) { var tempcanvas=document.createElement('canvas'); tempcanvas.width=1350; tempcanvas.height=1350; var context=tempcan ...

Troubleshooting: Vue.js file upload encountering OPTIONS 404 error

In my express app, I have configured CORS and most of the routes are working fine. However, I'm facing an issue with a specific component used for uploading images: <input type="file" class="form-control" @change="imageChanged"> <div @clic ...

In Node.js, it is essential to use req.session.save() to ensure that sessions are properly saved

While developing a website with Node.js, Express, and Redis for session management, I noticed an issue where my session variable (isLoggedIn) wasn't being saved after refreshing the page. Strangely, calling req.session.save() after setting the variabl ...

When PHP echo of json_encode triggers an error, AJAX status 200 will be raised

Despite everything running smoothly in the program below, an AJAX error is triggered: javascript: var data = { email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="026f6742656f636b6e2c616d6f">[email protect ...

I am looking for a way to access an array from Node.js using JavaScript and EJS. How can I achieve this

Currently, I am developing an app that requires passing an array from the server to the client. Initially, I attempted the following: // Server app.get('/', (req,res) => { res.render('index', { data: ["Hello"] }) }) ...

AJAX request returning null value to PHP validator

My current challenge involves sending an email to a PHP script in order to check for availability using ajax and an onKeyUp event in HTML. I've spent hours troubleshooting this issue, trying various approaches, but so far, I have not been able to fin ...

Error in Compiling HTML Elements Collection<<Element>

Currently, I am developing an eCommerce application that features a popup window for users when they click on "Add to Cart." This popup allows users to select product variations and quantities before adding the item to their cart. The popup consists of a s ...

When using console log, the object's keys and values display correctly, but they become undefined when attempting to access them

I am retrieving data from 2 different APIs - one for orders and one for workers. Both APIs have a workerId, so I need to link the information together to display each card with both order and worker details. For example, Order 1 - Tom, Order 3 - Jack... ...

"You are unable to modify headers once they have been sent to the client, and an unhandled promise has been

Every time I run this code block, I encounter the following error message - UnhandledPromiseRejectionWarning: Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client UnhandledPromiseRejectionWarning: Unhandled promise rejectio ...

The exported class does not properly recognize the input values, causing them to be displayed as Undefined and triggering an error

Currently working with Ionic Framework version 6.13.1, I have two services set up in a similar code structure. One is the appointment.service.ts, and the other is the registration.service.ts. Each service corresponds to its own TypeScript file containing a ...

Changing the alignment of checkboxes in HTML: a step-by-step guide

I'm encountering an obstacle when trying to adjust the alignment of checkboxes in my HTML code. Here is the structure of my HTML: <ol id="menutree"> <li> <label class="menu_label" for="c1">Menu Gen14 Am0a1</label> ...

Retrieve the JSON data by passing the variable name as a string

There are JSON files embedded in the page, like so: <script type="text/javascript" language="javascript" src="json/divaniModerni.json"></script> <script type="text/javascript" language="javascript" src="json/divaniClassici.json"></scr ...

Is it possible to implement a "load more" feature with JSON data using the getJSON method?

Currently, I am working on the task of extracting objects from a JSON file and arranging them in a grid layout similar to masonry using Salvattore. While I successfully utilized this helpful tutorial to retrieve the data, my next challenge is to implement ...

A simple guide on how to display a child object in a materialUI select dropdown from a parent object

I am developing a ReactJS application where I aim to showcase child objects from the parent object in a dropdown using materialUI select. Despite attempting to iterate over the object using the map() function, I haven't been able to retrieve values up ...

ReactJS not updating when multiple checkboxes are selected

Struggling to resolve an issue with this component. I encounter an error when trying to select multiple items using checkboxes. Oddly enough, another one of my components with the same code has no error. Please take a look at my code below, any help is gre ...

What is the method of showing a leaflet map in a particular div tag?

I want to showcase a leaflet map, but I specifically need it to be displayed in a div tag with a particular id like document.getElementById("map"). Here is the code snippet below which utilizes Vue.js: Here is the div tag where the map will be rendered: ...

Is there a way to locate the URL for a node.js express website hosted on a VPS?

Recently, I acquired a VPS from OVH to host my discord bot. The VPS comes with a stats.json page that I need to be accessed by another website using a GET request. However, I am unable to locate the express site for my VPS. I have been trying to access it ...

Can dynamic variables be incorporated within a const?

Could dynamic variables be used in the code below? const [viewport, setViewport] = useState ({ latitude:-8.683895, longitude:115.152307, width:800, height:440, zoom:16 }); I want the latitude and longitude to be flexible, like this: co ...

Guide on how to add the details of a specific id just once using PHP or jQuery

Is there a way to ensure that newly added data from SQL is only appended once? The current script I'm using displays the newly added data from SQL, but it keeps appending the same data multiple times. For example, if I add 'test by thisuser&apo ...