如何在不将变量定义为全局变量的情况下访问函数内部的变量

How to access a variable which is inside of a function without defining the variable as global

如何在不将变量定义为全局变量的情况下访问函数内部的变量。

function name() {
  var name2 = 20;
};

console.log(name2)

简短的回答是您不能访问在函数范围之外的函数内声明的变量

这里你试图访问 naem() 函数范围之外的 name2 变量,这是不可能的,因为用 var 关键字声明的变量只在它所在的块中可见已宣布。

如果你检查 the var MDN reference 你可以看到:

The scope of a variable declared with var is its current execution context, which is either the enclosing function or, for variables declared outside any function, global. If you re-declare a JavaScript variable, it will not lose its value.

更多详情您可以查看:

使用clauser:

function showName (firstName, lastName) {
var nameIntro = "Your name is ";
    // this inner function has access to the outer function's variables, including the parameter
function makeFullName () {     
return nameIntro + firstName + " " + lastName;
        
}

return makeFullName ();
}

console.log(showName ("Michael", "Jackson"));