How to access same variable name inside function in javascript

时间:2016-04-04 05:58:24

标签: javascript

How to access same variable name inside function in javascript

var xyz = "Hello";
console.log("outside function: " + xyz)
function abc() {
    var xyz = "World!";
    console.log("inside function: " + xyz) // output should be "Hello world!"
} abc();

4 个答案:

答案 0 :(得分:3)

尝试:

var xyz = "Hello";
console.log("outside function: " + xyz)
function abc() {
    var xyz = (window.xyz || "") +" " + "World!";
    console.log("inside function: " + xyz) // output should be "Hello world!"
} abc();

答案 1 :(得分:2)

如果您不想编辑xyz的值:

var xyz = "Hello";
console.log("outside function: " + xyz)
function abc() {
    var abc = " World!";
    console.log("inside function: " + xyz + abc) // output should be "Hello world!"
} abc();

如果你想编辑xyz的值:

var xyz = "Hello";
console.log("outside function: " + xyz)
function abc() {
    xyz += " World!";
    console.log("inside function: " + xyz) // output should be "Hello world!"
} abc();

答案 2 :(得分:2)

尝试使用窗口。这将允许您访问全局声明的变量。

var xyz = window.xyz ..

答案 3 :(得分:1)

为什么不把它作为参数传递? 绝对不需要使用global变量。

var xyz = "Hello";
console.log("outside function: " + xyz)
function abc(xyz) {
    var xyzUpdated = xyz + "World!";
    console.log("inside function: " + xyzUpdated) // output should be "Hello world!"
} abc(xyz);