Search code examples
javascriptscoping

Scoping when nesting objects/functions


I'm relatively new to JS and I'm trying to follow how scoping works with child objects/functions.

For example:

const b = {
  c: () => {
    console.log("C", foo)
  }
}
const x = (foo) => {
  console.log("X", foo)
  return {
    a: () => {
      console.log("A", foo)
    },
    b: b 
  }
}

i = x("FOO")
i.a()
b.c()

I'm hoping to see the output FOO in all 3 cases - however I actually see:

X FOO

A FOO

Uncaught ReferenceError: foo is not defined at Object.c

I'm trying to create a function where all it's methods are actually mapped to external/imported methods, but since these all need access to foo this isn't working. Is there a way in which b (c) can gain access to the foo? Or an alternative way of handling this situation?


Solution

  • You need to create b within the x function so that it can access the parameter value foo - it's not in scope otherwise. If you have to import b from somewhere else, you will need to change the other module to export a function so that you can provide foo for creating the b:

    function makeB(foo) {
      // `foo` is in scope here
      return {
        c() {
          console.log("C", foo)
        }
      };
    }
    
    function x(foo) {
      // `foo` is in scope here
      console.log("X", foo)
      return {
        a() {
          console.log("A", foo)
        },
        b: makeB(foo), 
      };
    }
    
    const i = x("FOO");
    i.a();
    i.b.c();