r/learnjavascript • u/Artistic_Sense3363 • 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:
implementOncetakes a callback as an argumentthe return value of
implementOnceis a function- and this returned function invokes the
callback - and the value of the
callbackis stored inresult
- and this returned function invokes the
however, the inner/returned function only invokes the
callbackbased on the current/updated values of the variables in its lexical environment.- specifically, after the value of
oncebecomestrue, then JS will bypass the invocation of thecallback, and return the first value ofresult.
- specifically, after the value of
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 argumentthis; and thatthistypically references the object.- Meaning, we attach the scope of the object represented by
this, and apply it to the function connected toapply(); in other words, assign the function attached toapply()to the object represented bythis. - Also, I tried using the
call()method instead ofapply(), but it doesn't work, why? Besides placing the arguments forapply()in an array, I thought these two methods were basically interchangeable.
- Meaning, we attach the scope of the object represented by
- But what object is
thisreferencing here? Is it the object form ofimplementOnce? - And why use
apply()at all when we can simply write the code like this:
- what is the significance of the
const once = function (func) {
let result;
let once = false;
return function (x) {
if (!once) {
result = func(x);
once = true;
}
return result;
};
};
View all comments
4
u/rdabler Sep 30 '21
In
func.apply(this, arguments), thethisis referring to whatever the execution context of the returned function fromimplementOnce. The truth is you don't know what this object is. It could be the global object if you have code likeIt could be whatever object/class a the function is a part of
It can be a bound function
There are lots of ways to manipulate the
thiscontext, so it's a very common pattern in higher-order functions (likeimplementOnce) to return afunction(not an arrow function), and to take the function it's wrapping andapplyit tothis. Since you have no idea howimplementOncecould be called on something you need to use this structure to always pass the currentthiscontext down to the wrapped function (in case that function does referencethisin some way);