Access global variable with same name as instance variable

Viewed 3805
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'

1 Answers

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

Related