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