如何使用相同的变量名称引用本地函数内的全局变量值

时间:2016-12-14 13:52:36

标签: javascript

在以下代码段中,我们如何在eval函数中将全局变量x值引用为product

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

2 个答案:

答案 0 :(得分:0)

您可以使用window对象将变量设为全局,并使用window.x来访问它。

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..

因此,只有在您需要to resolve conflicts时才需要应用更改。

答案 1 :(得分:0)

有多种方式: -

  1. 您可以存储与全局级对象关联的变量的全局版本,例如: -
  2. 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. 您可以使用 - ''变量
    2. 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" }

相关问题