Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access global variable with same name as instance variable

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'

like image 578
user7255069 Avatar asked Nov 06 '22 22:11

user7255069


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 })
like image 147
Phil Avatar answered Nov 11 '22 06:11

Phil