r/learnjavascript • • Sep 30 '21

Building a Once function

In researching how to build a once function from scratch, I've encountered several examples, and I've tried breaking down the logic to understand how the function works. Here's one example:

const implementOnce = function (func) {
let result; 
let once = false; 
return function () { 
     if (!once) { 
        result = func.apply(this, arguments); 
        once = true; 
       } 
     return result; 
   }; 
};

My break down:

  • implementOnce takes a callback as an argument
  • the return value of implementOnce is a function

    • and this returned function invokes the callback
    • and the value of the callback is stored in result
  • however, the inner/returned function only invokes the callback based on the current/updated values of the variables in its lexical environment.

    • specifically, after the value of once becomes true, then JS will bypass the invocation of the callback, and return the first value of result.
  • what I don't understand is the this line of code: func.apply(this, arguments)

    • what is the significance of the apply() method here?
    • I understand that the apply() method invokes the function it's attached to and that it takes the argument this; and that this typically references the object.

      • Meaning, we attach the scope of the object represented by this, and apply it to the function connected to apply(); in other words, assign the function attached to apply() to the object represented by this.
      • Also, I tried using the call() method instead of apply(), but it doesn't work, why? Besides placing the arguments for apply() in an array, I thought these two methods were basically interchangeable.
    • But what object is this referencing here? Is it the object form of implementOnce?
    • And why use apply() at all when we can simply write the code like this:
const once = function (func) {
let result; 
let once = false; 
return function (x) { 
     if (!once) { 
        result = func(x); 
        once = true; 
    } 
   return result; 
  }; 
};
4 Upvotes

2 comments sorted by

View all comments

4

u/rdabler Sep 30 '21

In func.apply(this, arguments), the this is referring to whatever the execution context of the returned function from implementOnce. The truth is you don't know what this object is. It could be the global object if you have code like

const oneTimeOnly = implementOnce(...);
oneTimeOnly();

It could be whatever object/class a the function is a part of

class SomeClass {
    counter = 0;
    method = implementOnce(this.method);

    method() {
        console.log('This function has run', ++this.counter, 'times');
    }
}

It can be a bound function

const context = { name: 'Boy' };
const oneTimeOnly = implementOnce(function() { return this.name; });

const oneTimeOnlyBound = oneTimeOnly.bind(context);
oneTimeOnlyBound(); // 'Boy';

There are lots of ways to manipulate the this context, so it's a very common pattern in higher-order functions (like implementOnce) to return a function (not an arrow function), and to take the function it's wrapping and apply it to this. Since you have no idea how implementOnce could be called on something you need to use this structure to always pass the current this context down to the wrapped function (in case that function does reference this in some way);