-2

In the following code snippet how can we refer the global variable x values as product in the eval function

<script type="text/javascript">
    var x = 'product';
window.onload = function() {
    function somefunction() {
        var x = 'boat';
        alert(eval('x'));
    }
    somefunction();
};

rumi
  • 3,293
  • 12
  • 68
  • 109
  • possible duplicate of http://stackoverflow.com/questions/2146173/how-to-get-local-variable-by-its-name-in-js?rq=1 – Alexis Dec 14 '16 at 13:55
  • There isn't a global variable `x` in that example code. – Quentin Dec 14 '16 at 14:09
  • 2
    And don't do that. Give your variables sensible, non-conflicting names instead. – Quentin Dec 14 '16 at 14:09
  • The solution is simple: don't overwrite your variable names. Since the name resolution is entirely lexical, that shouldn't be much of a problem to implement. – deceze Dec 14 '16 at 14:11
  • @Quentin I understand its not a good practice. I just wanted to clarify the concept – rumi Dec 14 '16 at 15:39

2 Answers2

0

You can use window object to make your variable global and use window.x to access it.

var x = 'product';

function somefunction() {
  var x = 'boat';
  console.log("logging global variable window.x: "+eval('window.x')); // resolve conflicts by using window.x
}
somefunction();

console.log("logging global variable x: "+ x); // access global variable..

So the changes you need to apply will be only when you want to resolve conflicts.

Rajshekar Reddy
  • 18,647
  • 3
  • 40
  • 59
  • @T.J.Crowder thanks I updated my answer, I initially tried in `jsFiddle` with `var x` but then the `window.x` showed undefined. Now I realize it was because if `jsfiddle` the code runs inside an `iframe` – Rajshekar Reddy Dec 16 '16 at 10:24
  • That's not why. It's because of jsFiddle's stupid *surprising* default of wrapping your code in a `window.onload = function() { ... };` handler. – T.J. Crowder Dec 16 '16 at 10:37
  • oh I get it.. I use it because even this code snippet of SO has lot of bugs.. I have lost my work many times – Rajshekar Reddy Dec 16 '16 at 10:38
0

there are multiple ways :-

  1. You can store the global version of variable , associated with a global level object like :-

var globalObject.x = "foo"; function test(){ x = "bar"; console.log(x); // it will print the local reference of x // "bar" console.log(globalObject.x); // it will print the global level x // "foo" }

  1. You can use - 'this' variable

var self = this; x = "foo"; function test(){ x = "bar"; console.log(x); // it will print the local reference of x // "bar" console.log(self.x); // it will print the global level x // "foo" }

Partha Roy
  • 1,575
  • 15
  • 16