Search code examples
javascriptjavascript-objectsnested-function

JavaScript Nested Functions cross referencing


I have a nested function that needs a return type of the previously declared function to use it as a function argument . I don't know if my structure is correct or can support this .

would be grateful for some advice on how to call it

  var myObject = {
     funct1 : (function (){..... return funct1; })(),
     funct2 : (function (funct1){..... return func2; })(funct1)
     };

So the question is how would I call that funct1 argument correctly in the second function

Do I use the myObject.Funct1 or is there another method of calling that object internally ...

Im currently getting a error

Cannot read property 'funct1' of undefined


Solution

  • I don't think there is a way to do this by declaring an object literal since the keys of the object can't be used during the object creation.

    You can get the same functionality by doing this, though:

    const myObject = (() => {
      const func1 = () => 'result of func1';
      const func2 = () => func1() + ' and func2';
      return { func1, func2 }
    })();
    
    console.log(myObject.func2()); // result of func1 and func2