dwigt
dwigt

Reputation: 611

Pass input parameters to returned JS functions

I am trying to pass input parameters from one function to another function inside a return statement. However in below example input1 and input2 are undefined. The values inside the return statement are undefined while inside the factory function they are not. How do I pass the values into the returned func()?

   function func(input1,input2) {
     console.log(input1,input2)
     // "undefined, undefined"
   }
    
    angular.module("factory").factory("test", (input1, input2) => {
     console.log(input1, input2)
     //"input1", "input2"
        return {
            func: (input1, input2) => {
                func(input1, input2);
            }
        };
    });

Upvotes: 0

Views: 135

Answers (2)

Tushar Shahi
Tushar Shahi

Reputation: 20626

The input1 and input2 in func : function are not the same as outside it. They are local params which will be passed on function call. You can omit input1 and input2 from the definition and call the function like this func().

console.log(input1, input2)
     //"input1", "input2"
        return {
            func: () => {        
               func(input1, input2);
            }
        };

Upvotes: 1

Yoshi
Yoshi

Reputation: 54659

This line:

func: (input1, input2) => {

shadows the parameter of the outer function (by declaring it's own parameters with the same names). So just remove those. E.g.

angular.module("factory").factory("test", (input1, input2) => {
    return {
        func: () => {
            func(input1, input2);
        }
    };
});

Upvotes: 1

Related Questions