简体   繁体   English

Javascript-全局变量和全局范围内的变量是否不同(在jsfiddle中)?

[英]Javascript - Are global variables and variables in global scope different (in jsfiddle)?

Are global variables and variables in global scope different? 全局变量和全局范围内的变量是否不同? Please see the code below or the JSfiddle implementation - http://jsfiddle.net/2ngj9rqa/ . 请参见下面的代码或JSfiddle实现-http: //jsfiddle.net/2ngj9rqa/

a = 10;
var b = 20;

function x() {
a = 20;
}

alert(window.a);
alert(window.b);

that's a trick in JSFiddle, b is wrapped in onload but not window if you choose no wrap , it's fine. 这是JSFiddle中的一个技巧,如果不选择no wrapb被包装在onload但不会包装在window ,这很好。 Also try the same in plunker is fine. 也可以在punker中尝试同样的方法。

The code you've written will work fine in all major browsers.It won't work because it is wrapped by onload in jsfiddle.Both a and b are global variables here and both of them are in global scope. 您编写的代码在所有主流浏览器上都可以正常工作,因为它被jsfiddle中的onload包裹了,所以无法正常工作.a和b都是全局变量,并且都在全局范围内。 You can access them from anywhere in your code unless you introduce a variable with same name inside a function's own scope.There is something called variable scoping and hoisting.All the variables(except implicit global) are hoisted at the top of its scope when you declare a variable or assign value to it( with var keyword ofcourse ) . 您可以在代码的任何位置访问它们,除非您在函数自己的作用域内引入一个具有相同名称的变量。有一种称为变量作用域和提升的方法。声明变量或为其赋值( 使用var关键字ofcourse )。 know more on variable and function hoisting So,your code is equivalent to this: 了解有关变量和函数提升的更多信息,因此,您的代码等效于此:

var b;

a = 10;
b = 20;

function x() {
a = 20;
}

alert(window.a);
alert(window.b);

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

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