Javascript 如果变量为';JS中的花括号外有什么?

Javascript 如果变量为';JS中的花括号外有什么?,javascript,Javascript,我不明白这一点-如果在条件之外使用条件,那么在中定义的var如何才能在该条件之外使用 示例JS: if (1===2) { var myVar = "I live in brackets"; } $("#debug").append("myVar = " + myVar); $("#debug").append("but I'm about to throw a 'not defined' exception right... now " + firstAppearanceVar); 呈现

我不明白这一点-如果在
条件之外使用
条件,那么在
中定义的
var
如何才能在该条件之外使用

示例JS:

if (1===2) {
  var myVar = "I live in brackets";
}
$("#debug").append("myVar = " + myVar);
$("#debug").append("but I'm about to throw a 'not defined' exception right... now " + firstAppearanceVar);
呈现:
myVar=I生活在括号中


如果(1==2)
条件,myVar的作用域不只是在
的范围内吗?

作用域只适用于函数,而不是其他块。

作用域只适用于函数,而不是其他块。

Javascript没有块作用域,它只有函数作用域

alert(foo); // undefined (no error because of the hoisting.)
var foo = 2;
alert(bar); Error

换句话说,
var
声明的变量可以在函数的作用域内访问,无论在何处,就在那里,而不是在外部。

Javascript没有块作用域,它只有函数作用域

alert(foo); // undefined (no error because of the hoisting.)
var foo = 2;
alert(bar); Error
换句话说,
var
声明的变量可以在函数范围内访问,无论在何处,就在那里,而不是在函数范围之外。

因为,每个变量声明都会弹出到函数范围的顶部

alert(foo); // undefined (no error because of the hoisting.)
var foo = 2;
alert(bar); Error
由于,每个变量声明都会弹出到函数范围的顶部

alert(foo); // undefined (no error because of the hoisting.)
var foo = 2;
alert(bar); Error

定义javascript变量后,声明将被提升到函数范围的顶部

alert(foo); // undefined (no error because of the hoisting.)
var foo = 2;
alert(bar); Error
因此:

if (1===2) {
  var myVar = "I live in brackets";
}
$("#debug").append("myVar = " + myVar);
$("#debug").append("but I'm about to throw a 'not defined' exception right... now " + firstAppearanceVar);
相当于这个

var myVar;
if (1===2) {
  myVar = "I live in brackets";
}
$("#debug").append("myVar = " + myVar);
$("#debug").append("but I'm about to throw a 'not defined' exception right... now " + firstAppearanceVar);
因此,函数中定义的任何变量都可以在该函数中的任何位置或任何内部函数中访问。在功能外部无法访问它们

所以


定义javascript变量后,声明将被提升到函数范围的顶部

alert(foo); // undefined (no error because of the hoisting.)
var foo = 2;
alert(bar); Error
因此:

if (1===2) {
  var myVar = "I live in brackets";
}
$("#debug").append("myVar = " + myVar);
$("#debug").append("but I'm about to throw a 'not defined' exception right... now " + firstAppearanceVar);
相当于这个

var myVar;
if (1===2) {
  myVar = "I live in brackets";
}
$("#debug").append("myVar = " + myVar);
$("#debug").append("but I'm about to throw a 'not defined' exception right... now " + firstAppearanceVar);
因此,函数中定义的任何变量都可以在该函数中的任何位置或任何内部函数中访问。在功能外部无法访问它们

所以


因此,JS和C在这方面肯定有区别。考虑到名字不同,是的,我会说它们不同!我只是说b/c在两种语言中的语法是相似的。@IanDavis,不,c#和js是完全不同的,不像C#。差异很大。ohh和C#不是一种动态语言。。。有点不同。所以,在这一点上,JS和C当然有区别。考虑到名字不同,是的,我会说它们不同!我只是说b/c在两种语言中的语法是相似的。@IanDavis,不,c#和js是完全不同的,不像C#。差异很大。ohh和C#不是一种动态语言。。。有点不同。在javascript中,作用域是按函数划分的
if(){}
没有自己的作用域mdn是学习javascript的一个很好的资源:在javascript中,作用域是按函数定义的
if(){}
没有自己的作用域mdn是学习javascript的一个很好的资源:但是,我在页面上没有任何函数。在这种情况下,JS是否将这一切都视为一个包装函数的保护伞下?@IanDavis,如果它不在函数中,它就在全局对象中。但是,我在页面上没有任何函数。在这种情况下,JS是否将这一切视为一个包装函数的保护伞下?@IanDavis,如果它不在函数中,那么它就在全局对象中。