skip to Main Content
function mainFunc(mainParameter) {
 return {
  subFunc1 : function (sub1Parameter) {
   return sub1Parameter;
  },
  subFunc2 : function (sub2Parameter) {
   return sub2Parameter
  }
 }
}

// This works
console.log(mainFunc().subFunc1('example text'));

// I need this
console.log(mainFunc('example text'));

How can i use ‘return’ with mainFunc() like last line in the code block.

2

Answers


  1. You can add an if to see if mainFunc was called with any arguments, then if mainFunc was called with an argument, have it do whatever it is it’s supposed to do with that parameter instead of returning the object, like this:

    function mainFunc(...args) {
        if (args.length !== 0) {
            // Do whatever it's supposed to do when it gets an argument
            console.log("(Got an argument)");
            return args[0];
        }
        // Didn't get any arguments
        console.log("(Didn't get any arguments)");
        return {
            subFunc1: function (sub1Parameter) {
                return sub1Parameter;
            },
            subFunc2: function (sub2Parameter) {
                return sub2Parameter;
            },
        };
    }
    
    console.log(mainFunc().subFunc1("example text"));
    
    console.log(mainFunc("example text"));
    Login or Signup to reply.
  2. if you need only the second type of output console.log(mainFunc('example text')); you can do this way:

    function mainFunc(mainParameter) {
    
     return {
    
      subFunc1 : function (sub1Parameter) {
          return sub1Parameter;
      }(mainParameter),
    
      subFunc2 : function (sub2Parameter) {
          return sub2Parameter
      }(mainParameter)
    
     }
    
    }
    

    Otherwise this one works in both cases:

    function mainFunc(mainParameter) {
    
        const subFunc1 = function (sub1Parameter) {
            return sub1Parameter;
        };
    
        const subFunc2 = function (sub2Parameter) {
            return sub2Parameter;
        };
    
        if (mainParameter)
            return {subFunc1: subFunc1(mainParameter), subFunc2: subFunc2(mainParameter)}; 
     
        return {subFunc1: subFunc1, subFunc2: subFunc2}; 
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search