-1

Say I have a parent function that calls some child functions like this:

function parentFn() {
   API.greet();
}
parentFn.name = 'john';

const API = {
   greet: function() {
       console.log(`Hi there ${parentFunc.name}`); // prints out 'Hi there undefined'
   }
};

parentFn()

Is there anyway to get a property of the parent function inside the API without adding a parameter to the inner function?

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
MarksCode
  • 8,074
  • 15
  • 64
  • 133
  • 1
    Why not add a parameter? – obe May 07 '21 at 16:10
  • 1
    The code you've provided won't do what you've said it will do. It will throw an error because you have `parentFn` in one place but `parentFunc` in another. If you had `parentFn` throughout, you'd get `Hi there parentFn` because the `name` property of a function is read-only. – T.J. Crowder May 07 '21 at 16:12
  • I've put the code in the question into a Stack Snippet. I didn't fix the apparent typo because it's not clear to me whether you meant to do something else entirely. – T.J. Crowder May 07 '21 at 16:13
  • 1
    When you say _parent function_ do you mean the function that called your function? Like, one level beneath you on the call stack? If so, see [How do you find out the caller function in JavaScript?](https://stackoverflow.com/questions/280389/how-do-you-find-out-the-caller-function-in-javascript) – Wyck May 07 '21 at 16:18
  • 1
    Please tell us more about your actual use case so that we can find an idiomatic solution. – Bergi May 07 '21 at 16:22

1 Answers1

-1

There are two cases:

  • Every "child" function can have only a single "parent". If so, just refer to that specific parent directly: parentFn.name.
  • Every "child" function can be called by multiple others. In this case you need a parameter for the dynamic value.

Notice that if you don't want to declare an explicit parameter, you might able to use the implicit parameter this that every function and method has. It normally points to the API object in a API.greet() call, but you can change it like API.greet.call(parentFn) (although this is slightly weird).

Bergi
  • 630,263
  • 148
  • 957
  • 1,375