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

Categories

0 votes
3.8k views
in Technique[技术] by (71.8m points)

How to make variables accessible outside of their scope in JavaScript

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...