在以下代码段中,我们如何在eval函数中将全局变量x
值引用为product
<script type="text/javascript">
var x = 'product';
window.onload = function() {
function somefunction() {
var x = 'boat';
alert(eval('x'));
}
somefunction();
};
答案 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)
有多种方式: -
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"
}
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"
}