RaphaMex
RaphaMex

Reputation: 2839

Can't get `arguments` of inner arrow function

I was making a decorator function in response to this question when I realized it was not working as expected. The function simply counts how many times given function is called, and logs it.

function countExecutions(fn) {
    let count = 0;
    return () => {
        console.log("called",++count);
        return fn.apply(this, arguments);;
    }
}

var test = countExecutions((a,b) => a+b);
var x = test(1,2);
console.log(x); // (a,b) => a+bundefined

I realized this is because arguments refer to the arguments of the function countExecutions instead of my inner anonymous function. So it logs (a,b) => a+bundefined instead of 3. Why can't I get arguments of inner anonymous function?

If I give it a name, it works as expected:

function countExecutions(fn) {
    let count = 0;
    return function inner() {
        console.log("called",++count);
        return fn.apply(this, arguments);;
    }
}

var test = countExecutions((a,b) => a+b);
var x = test(1,2);
console.log(x); // 3

Upvotes: 0

Views: 93

Answers (3)

Cody Geisler
Cody Geisler

Reputation: 8617

I think you're misunderstanding arrow functions, here's your anonymous (not using the arrow function) version:

(Alternatively you can use arrow functions as noted in @trincot's answer. )

function countExecutions(fn) {
    let count = 0;
    return function(){
        console.log("called",++count);
        return fn.apply(this, arguments);;
    }
}

var test = countExecutions((a,b) => a+b);
var x = test(1,2);
console.log(x); // (a,b) => a+bundefined

Upvotes: 3

trincot
trincot

Reputation: 350781

As stated, arguments is not defined for arrow functions. But why not use the spread syntax:

function countExecutions(fn) {
    let count = 0;
    return (...args) => {
        console.log("called",++count);
        return fn.apply(this, args);
    }
}

var test = countExecutions((a,b) => a+b);
var x = test(1,2);
console.log(x); // 3

Upvotes: 2

TimoStaudinger
TimoStaudinger

Reputation: 42490

It doesn't behave this way due to the function being named, but because you're using an arrow function. Arrow functions not only do not define their own function scope, but also no arguments:

An arrow function expression has a shorter syntax than a function expression and does not have its own this, arguments, super, or new.target. These function expressions are best suited for non-method functions, and they cannot be used as constructors.

Source

Upvotes: 1

Related Questions