简体   繁体   English

JavaScript函数变量范围

[英]JavaScript function variable scope

In the following code, why can I access the variable xb? 在下面的代码中,为什么我可以访问变量xb? Shouldn't it have a local scope? 它不应该有本地范围吗?

CODE

function x() {
    var a = 3;
}


x.b = 8;

console.log(x.a);
console.log(x.b);

OUTPUT OUTPUT

undefined
8

When you use var to declare a within x 's constructor, a is mark as private, however when you do xb you are essentially saying - add the property b to the object x . 当你使用var来声明a x的构造函数时, a标记为private,但是当你执行xb你实际上是在说 - 将属性b添加到对象x

Hence when you do xb , technically speaking you are accessing object x 's property b , which is 8. 因此,当您执行xb ,从技术上讲,您正在访问对象x的属性b ,即8。

You have defined xb to 8 and it becomes a global var. 您已将xb定义为8,它将成为全局变量。 Which means you can access it from anywhere. 这意味着您可以从任何地方访问它。

So the x() is a function which has its own scope. 所以x()是一个有自己范围的函数。 So you can't access the vars inside a function scope in the mentioned way. 因此,您无法以上述方式访问函数范围内的变量。 However you can access the 'a' by doing this and calling the x function. 但是,您可以通过执行此操作并调用x函数来访问“a”。

function x() {
  var a = 3;
  return a;
}

Javascript considers xb as a global object. Javascript将xb视为全局对象。 so you can access it even inside the function like: 所以你甚至可以在函数内访问它:

x.b = 8;
function x() {
    var a = 3;
    alert(x.b)
}
x();
console.log(x.a);
console.log(x.b);

But make sure you specify xb before function declaration. 但请确保在函数声明之前指定xb。

whereas object a is specified inside the function x() which makes it private thats why you are getting undefined result for console.log(xa); 而在函数x()中指定了对象a,这使得它变为私有,这就是为什么你得到console.log(xa)的未定义结果的原因;

if you write it like this: 如果你这样写:

a = 5;
function x() {
    var a = 3;
}
x.b = 8;

alert(a);
alert(x.b);

you will get results as bellow: 你会得到如下结果:

5
8

for javascript a and xa are two separate objects. 对于javascript a和xa是两个独立的对象。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM