5
var myVar = 5;

var example = function() {
   var myVar = 10;

   // How can I access the global variable 10?
};

If there is a global variable with the same name as a local variable, how can I access the global one?

I am not using es6.

I am running it in jsdb, not a browser or node so I do not have access to objects 'Window' or 'global'

2
  • If there is no global object, I don't think it's possible. Best to use different variable names regardless, though. Commented Jan 14, 2019 at 2:11
  • How / where are you calling example()? Are you able to alter that code at all? Commented Jan 14, 2019 at 2:13

1 Answer 1

2

Assuming you can alter the code calling your example() function, you should be able to pass the current scope using Function.prototype.call() and access it using this. For example

'use strict'

var myVar = 5;

var example = function() {
   var myVar = 10;
   
   console.info('Local:', myVar)
   console.info('Outer:', this.myVar)
};

example.call({ myVar })

Sign up to request clarification or add additional context in comments.

4 Comments

Thanks... I guess I'm confused on why 'this' accesses the global scope as opposed to the local scope, while inside the example function. Can you explain that more for me?
It doesn't. this in the function access the function's context. The handy thing about Function.prototype.call means you can supply this context. For example, if you used .call({a: 1}) then this.a would be 1.
This answer uses ES6 which would be fine but the OP says he is not using ES6. Just change { myVar } to { myVar: myVar }
@PHPGuru yet OP accepted the answer 🤔

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.