Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I am new to JavaScript and learning about scope. I understand that there is Global Scope and Local Scope, but wanted to know if variables in the Local scope could be made available outside their scope.

Is this possible, and if so how?

Thank you to everyone with the quick responses.

I'm learning to program and I had an outline made up on topics to research from a programmer. They said there is a way and even though it is bad practice, this could be used as a developer tool and there are some scenarios this would be helpful in.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
3.5k views
Welcome To Ask or Share your Answers For Others

1 Answer

You can assign them to globalThis (also known as window in the browser and global in node):

function assignGlobal(x) {
  globalThis.globalVar = x;
}

console.log(globalThis.globalVar);

assignGlobal('foo');

console.log(globalThis.globalVar);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...