问题描述
我目前正在用Pragmatic阅读一本关于Javascript的书,而我对一件事感到困惑。他们有一个关于如何使变量为全局,局部或私有的部分。
-
局部变量和私有变量之间有什么区别?是否有一个?
-
如何做一个全局变量或局部变量,他们说了一些关于把'var ='放在它之前,但它非常含糊。 使用私人,因为他们是错误的,并且是为了说本地。
局部变量被定义为
var foo =local;
全局变量是全局作用域对象(在浏览器中是 window
)的属性
window.foo =global;
您可以这样做 foo =global;没有先用
这是固定在ES5严格模式。 var foo
分配变量foo就是一个bug,那么
(function(){use strict; foo = 42;})()
$ b $ p给出 ReferenceError:foo未定义
请注意,您可以通过在最外层范围声明变量来使变量成为全局变量
var foo =global;
函数bar(){
var foo =local;
}
应该注意的是,您不应该在最外面的范围内有任何代码,永远。你应该把所有的作用域都包含在匿名函数中,这样你才能获得模块级作用域。这意味着你有一个基于每个文件的顶级范围。这是模块模式的一部分。
I am currently reading a book on Javascript by Pragmatic, and I'm confused about one thing. They have a section on how to make variables global, local, or private.
What is the difference between local and private variables? Is there one?
How does one make a variable global or local, They said something about putting 'var =' before it, but it was very vague.
None, People use "private" because they are mistaken and are meant to say "local"
local variables are defined as
var foo = "local";
global variables are a properties of the global scope object (which is window
in the browser)
window.foo = "global";
The fact you can do foo = "global";
without first assigning variable foo with var foo
is a "bug". This is fixed in ES5 strict mode.
(function () { "use strict"; foo = 42; })()
gives ReferenceError: foo is not defined
Note that you can make variables global by declaring them in outer most scope
var foo = "global";
function bar() {
var foo = "local";
}
It should be noted that you shouldn't have any code in outer most scope, ever. You should be wrapping all your scope in anonymous functions so that you get "module level scope". This means you have a per file based top level scope. This is part of the module pattern.
这篇关于全局和本地和私有函数(Javascript)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!