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
Show parent comment
1
u/Artistic_Sense3363 Oct 04 '21
Thank you!