Home > Mobile >  Why global scope can not be accessed in this case?
Why global scope can not be accessed in this case?

Time:12-17

I faced this issue recently. I could pass the problem, but I didn't get the concept behind it. If you try the snippet, you see what's going on. Can someone explain it?

function func1() {
  console.log('Func1 executed.');
};

const func2 = () => {
  console.log('Func2 executed.');
};

const test = () => {
  window['func1'](); //Working
  window['func2'](); //Not working
};
button {
  width: 200px;
  padding: 20px;
  font-size: large;
  cursor: pointer;
  border: 0;
  background: linear-gradient(to top right, gray, silver);
  color: white;
  border-radius: 7px;
  box-shadow: 0px 5px 7px silver;
  text-shadow: 0px 2px 2px rgba(0,0,0,0.5);
}
<button onclick='test()'>Execute</button>

CodePudding user response:

The straightforward answer is:

Global variables initialised with let and const do not become properties of window.

See:

const

Global constants do not become properties of the window object, unlike var variables

Source: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/const

and:

let

Just like const the let does not create properties of the window object when declared globally (in the top-most scope).

Source: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/let

CodePudding user response:

I'm not very experienced with JS, but I believe is because the first one is actually a function that can be reused multiple time, where the second one is lambda function with the purpose to returning and storing a value (but not recompute) into the func2 var.

Correct me if I'm wrong.

CodePudding user response:

The issue is that you are really calling a value/variable (const func2 = could end with a int for example.) You need to pass a function itself int tohe format window[Functioname]().

You can do this through 2nd degree function calling, see below.

Nice button by the way.

function func1() {
  console.log('Func1 executed.');
};
const func2 = () => {
  console.log('Func2 executed.');
};


function func3(){
  func2();
}
const test = () => {
  window['func1'](); //Working
  window['func3'](); //Working
  window['func2'](); //Not working
};
button {
  width: 200px;
  padding: 20px;
  font-size: large;
  cursor: pointer;
  border: 0;
  background: linear-gradient(to top right, gray, silver);
  color: white;
  border-radius: 7px;
  box-shadow: 0px 5px 7px silver;
  text-shadow: 0px 2px 2px rgba(0,0,0,0.5);
}
<button onclick='test()'>Execute</button>

  • Related