In what way is the reference to "this" passed in the function that follows?

I came across the following example in the JS manual, which is functioning correctly:

let worker = {
  someMethod() {
    return 1;
  },

  slow(x) {
    alert("Called with " + x);
    return x * this.someMethod(); // (*)
  }
};

function cachingDecorator(func) {
  let cache = new Map();
  return function(x) {
    if (cache.has(x)) {
      return cache.get(x);
    }
    let result = func.call(this, x); // now 'this' is passed correctly
    cache.set(x, result);
    return result;
  };
}

worker.slow = cachingDecorator(worker.slow); // now make it a caching function

alert( worker.slow(2) ); // works
alert( worker.slow(2) ); // works without calling the original function (caching activated)

My question is about how the reference to "this" gets passed into the cachingDecorator function, when cachingDecorator is not declared inside of the object and is called as

worker.slow = cachingDecorator(worker.slow)
? I am referring specifically to this line inside the cachingDecorator: let result = func.call(this, x).

Answer №1

this pointer gets passed in the final two rows during the application of the decorator, especially when the worker object comes before the period.

Answer №2

The this keyword is not actually defined within the cachingDecorator function, but instead within the anonymous function that is being returned. Therefore, the value of this is determined only when that particular function is called.

Since this function is assigned to worker.slow and called from within the context of the worker object, the value of this is set to refer to the worker object.

It is important to understand that this behaves like a distinct type of function parameter. It does not exist with a conventional name like other parameters, but rather gets its value based on how the specific function is invoked, unlike regular parameters which are passed as arguments in a typical manner.

Answer №3

The function called cachingDecorator should be noted as returning a new function declared in the format function(x) {. . .}. When this type of function is invoked using an object reference, it will inherit that object's context:

function magicFn() { return this }
const x = { magicFn };
const y = { someKey: 6, magicFn };
x.magicFn(); // The result will be x, since it was called as x.magicFn
y.magicFn(); // The result will be y
magicFn(); // The result will be undefined, as there is no `this` object member reference

Therefore, when

worker.slow = cachingDecorator(worker.slow)
is executed, the resulting function calls the original worker.slow using worker.slow.call(this, x);, which forwards the incoming value of this (in this case, worker).

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

Is it possible to launch a Nextjs app on Vercel for production purposes? How well does it handle high volumes of traffic?

As a newcomer to Nextjs, I am looking to deploy my app to production. I'm curious about whether Vercel can effectively handle heavy traffic on the site. Should I consider utilizing platforms such as AWS or GCP for deployment instead? Any advice would ...

The pop-up menu appears in a location different from where the anchor element is positioned

Having an issue with the menu placement when clicking on an Avatar. The menu is appearing in the wrong position: https://i.sstatic.net/955eJ.png The avatar button "OB" on the right side is where the issue occurs. No console errors present and inspecting ...

Upgrade to a more stable configuration version for Nodemailer as the current configuration is not supported. Consider down

I'm currently utilizing Nodemailer version 2.6.4 with Node version 6.9.1 var nodemailer = require("nodemailer"); var wellknown = require('nodemailer-wellknown'); var transporter = nodemailer.createTransport("SMTP",{ service: "yahoo", ...

results vary when using both a while loop and callback

I'm having an issue with my while loop when filtering data from mongodb. Even though I should be getting three entries logged to the console, only one entry is making it to the callback function. Can anyone explain why this is happening? while(i--) { ...

Ways to transfer GET form information to Express?

I am working on a form that needs to pass parameters correctly <form action="./search" method="GET"> <div class="form-group text-center"> <input type="text" name="keyword" placeholder="Search Term" /> ...

Browser tries to interpret Javascript code as a file organization system

Encountering an issue while trying to load my website. When I open index.html in my browser, I receive a problem loading page message. This response is puzzling as it does not indicate a file loading error. Here's a snippet of the response: Firefox c ...

I have a query regarding the load function and JSON

Is it feasible to achieve something similar to this? $.ajax({ url: "test.php", success: function(json, json1){ //I wonder if I can have more than one parameter here? $m0 = []; $m0.push(parseFloat(json)); alert($m0); //display 750 $m1 ...

Concentrate on Managing Text Input Fields in Zend Form

I designed a form using Zend Form and want the focus to be on a text area within the form when the page loads. I attempted to use JavaScript for this purpose, but it only briefly shows the focus before removing it again, preventing any typing. I considere ...

Utilizing an imported variable beyond a component function within React useEffect: A comprehensive guide

I'm encountering a problem while trying to utilize the imported variable likedImages within a useEffect hook in a React component. When I include likedImages in the dependency array, I receive a warning indicating that it is an unnecessary dependency ...

Each time the Angular children component is reloaded, the user is redirected to localhost:4200

In my Angular project, I encounter an issue with route parameters in children components. While navigating to these child components from the parent is seamless, reloading the child component causes the application to redirect to localhost:4200 and display ...

The abort() function in Chrome can trigger an Undefined Error

When dealing with race conditions, I implement the following code to throttle get requests: if (currentAjaxRequest !== null) { currentAjaxRequest.abort(); } var query_string = getQuery(); currentAjaxRequest = ...

Implement a dropdown menu for filtering, but it is currently not functioning as expected

When I select a city_name, my goal is for the graph to only display information pertaining to that particular city. In the params section of my code, I have included filtering options using a selection menu in Vega-Lite. However, despite selecting Brisba ...

The JQuery function .load() is not functioning correctly

How can I dynamically load a webpage's content into a div using JavaScript and jQuery? Here's what I have tried: <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script> When a s ...

Issue with triggering blur event in Internet Explorer while using Angular 2+

The issue discussed in the Blur not working - Angular 2 thread is relevant here. I have a custom select shared component and I am attempting to implement a blur event to close it when the component loses focus. // HTML <div (blur)="closeDropDown()" t ...

When async/await is employed, the execution does not follow a specific order

I'm curious about the execution of async/await in JavaScript. Here are some example codes: async function firstMethod(){ new Promise((resolve, reject)) => { setTimeout(() => { resolve("test1"); }, 3000); }); } async ...

Repetitive occurrences of events being emitted from a VueJS component

As my mouse cursor hovers over and exits my VueJS component, specific methods are triggered accordingly. The methods that execute when the cursor enters and leaves my component: // Included in the "methods" section of my Vue component file onMouseEnter( ...

Preparing user context prior to executing controllers within AngularJS

I recently created an AngularJS application and integrated a REST API to fetch resources for the app. As part of the authentication process, I store the user's access token in a cookie. When the user reloads the page, I need to retrieve user informati ...

Using a Vuejs web component as an input element in a non-Vue web application: A step-by-step guide

After creating a web component with VueJs using VueCli3, the compiled output appears as follows: <script src="https://unpkg.com/vue"></script> <script src="./my-lib.js"></script> <my-lib></my-lib> This particular web ...

What is the best way to share image data between pages in Next.js?

I'm currently developing a project that mimics Instagram (simply because I want to explore Next.js further) and I'm looking for a way to handle image uploads. My goal is to allow users to upload their images and then redirect them to the "create ...

Encountering issues due to overriding JSON.stringify

Recently, I developed a customized function for JSON.stringify implementation as shown below: JSON.stringify = function (item, replacer, space) { return JSON.stringify(item, replacer, space); } This modification led to multiple errors in AngularJS w ...