The following function once (problem 13) will take func and return a function that allows func to be called only once.
function add(a, b) {
    return a + b;
}
function once(func) {
    return function () {
        var f = func;
        func = null;
        return f.apply(this, arguments);
    };
}
add_once = once(add);
add_once(3, 4)   // 7
add_once(3, 4)   // throws
There are two things that I don't get about this.
- Why does writing func = nullstop us from calling the function a second time? After saving the pointer to the function (it's all right to use the C lingo; isn't it?) invar f = func, I'd expect that assigningnullto the function pointerfunc(funcis just a function pointer; isn't it?) is irrelevant—because the (pointer to the) function is already stored inf. What am I missing?
- I get that it's necessary to write f.apply(this, arguments);rather than simplyf(arguments);because it's one of JavaScript's idiosyncrasies. The latter would send an array, not a list of arguments, to the function. But I don't get whatthisrefers to. Does it refer to the anonymous function on the second line or toonce? And if assigningfunc = nullis meant to stop the second invocation because the closure will lead to afuncthat has been nulled, why does it work the first time it's called?
I am using too many questions to give you the chance of identifying what I'm missing, not with the expectation that you'd type a long answer addressing each sub-question independently.
 
     
     
    