Can I transfer the scope of a function to another when calling it?

Can I transfer the scope of a function to another when calling it?

Problem Description:

function parent() {
    let name = 'joe';
    printName();

    function printName() {console.log(name)}
}

this works, but i want to move printName outside of the other function.

function parent() {
    let name = 'joe';
    printName();
}
function printName() {console.log(name)}

but this does not work, since name is stuck inside the parent function. Is there a way to send the current scope of parent to printName when I call that function on line 3? something like .bind but for all variables not just this

Solution – 1

Is there a way to send the current scope of parent to printName when I call that function on line 3? something like .bind but for all variables not just this

No. But here are two alternatives:

  1. Use functional programming techniques: create a name parameter for the printName function and provide the name argument when invoking it:
function printName (name) {
  console.log(name);
}

function parent () {
  let name = 'joe';
  printName(name);
}

parent(); // logs "joe"
  1. Initialize an object that is in scope for both functions and mutate its properties. In this second approach, both functions are closures because they depend on the reference to obj being available when they are invoked:
const obj = {};

function printName () {
  console.log(obj.name);
}

function parent () {
  obj.name = 'joe';
  printName();
}

parent(); // logs "joe"

The second approach is conceptually like assigning properties to the global object, but it avoids global scope pollution.

Rate this post
We use cookies in order to give you the best possible experience on our website. By continuing to use this site, you agree to our use of cookies.
Accept
Reject