Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to access a variable from the caller's scope inside a function in JavaScript?

This question has been asked before, but all of the popular questions are 5+ years old and I'm curious to know if anything has changed since then. If you have a function that's defined somehwere

const accessParentScope = () => parentVariable;

then is there any way to access a parentVariable from the scope where the function is called? The end goal would be to do something like

function createAnotherScope() {
  const parentVariable = 'some value';
  return accessParentScope();
}

and have accessParentScope() have access to parentVariable without explicitly passing it as an argument.

Alternatively, is it possible to access variables from the scope of a closure? If you have a function like

function createClosure() {
  const parentVariable = 'some value';
  return closure = () => null;
}

then can you do something like createClosure().parentVariable? The syntax here obviously won't work, but I'm curious if anything remotely like this is possible.

like image 431
Ivanna Avatar asked Sep 06 '26 02:09

Ivanna


1 Answers

Is it possible to access a variable from the caller's scope inside a function in JavaScript?

No. That would be dynamic scope. Most languages (including JavaScript) implement lexical scope. That is not going to change.

There is this, but it's rather an explicitly passed argument. The value of this is (in most cases) determined when the function is called, not when or where it is defined (arrow functions treat this differently though).

function logName() {
  console.log(this.name);
}

function sayFoo() {
  logName.call({name: 'foo'});
}
sayFoo();

function sayBar() {
  logName.call({name: 'bar'});
}
sayBar();

As you can see, there really isn't any advantage of this over defining the function with parameters:

function logName(name) {
  console.log(name);
}

function sayFoo() {
  logName('foo');
}
sayFoo();

function sayBar() {
  logName('bar');
}
sayBar();

As @JaromandaX said in their comment, that's what parameters are therefore, to provide values to the function at call time.

like image 140
Felix Kling Avatar answered Sep 08 '26 01:09

Felix Kling



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!