我正在阅读JS书中关于闭包的部分,并在显示'getter / Stetter'函数的部分中找到了一个例子......
var getValue, setValue;
(function (){
var secret = 0;
getValue = function(){
return secret;
}
setValue = function(v){
secret = v;
}
})();
setValue(5);
getValue();
5 //get 5
1)我认为省略'var'使变量成为全局变量?
2)我不时会听到人们谈论'getter / Setters',他们会有什么实际用途?
谢谢!
答案 0 :(得分:1)
为什么'秘密'变量不是全局变量?
因为它是使用var
声明的。
var secret = 0;
我认为省略'var'使变量成为全局变量?
在函数中使用var
将使该语句中声明的所有变量都是本地的。
答案 1 :(得分:1)
Javascript有functional scope,因此secret
变量仅存在于函数范围内。
var iAmGlobal = true;
iAmGlobalToo = true; // no var made this an implied global
(function () {
var iExistInThisFunctionsScope = true;
iAmAnImpliedGlobal = true; // omitted var attached this to the global scope
}());
省略var
并不一定会使变量成为全局变量。发生的情况是,当在当前作用域中找不到变量时,将检查父作用域。在找到变量或达到global
范围之前,会发生这种情况。当您意外忘记var
时,您通常会以隐含的全局结束。
What are some of the problems of "Implied Global variables"?
使用closures创建getter / setter可以控制变量的修改方式。因为在Javascript中一切都是可变的,任何其他东西都可以改变。这一开始看起来很酷,但你很快意识到你无法控制改变变量的人或者是什么。 getter和setter允许你在函数的范围内隐藏变量,所以如果想要改变它,它必须通过你。
以下是控制变量的示例。
function Foo () {
var privateVar = 1234;
this.get = function () {
return privateVar;
}
this.set = function (x) {
// privateVar doesn't exist in this function's scope,
// but it will be found in the next scope up the chain.
privateVar = x;
}
}
// create an instance
var myFoo = new Foo();
// use the getter/setter
console.log(myFoo.get()); // 1234
myFoo.set(999);
console.log(myFoo.get()); // 999
// try to change privateVar outside
// of the getter/setter
myFoo.privateVar = 'not what you think';
// We didn't actually change the var.
console.log(myFoo.get()); // 999
// We added a new property.
console.log(myFoo.privateVar); // 'not what you think'
答案 2 :(得分:0)
因为它是在(function() { ... })
内定义的。如果您想将其设为全局,请将其与getValue
和setValue
一起声明。
var
关键字只是声明一个变量,它不会使其成为全局:
var secret = "Global"; // Global variable declaration
function myFunction() {
var secret; // Local to myFunction()
secret = "Hello, world!"; // Only local secret variable changed
console.log(secret); // "Hello, world!"
}
console.log(secret); // "Global"
如果已在全局范围内定义变量,则删除var
只会使其成为全局:
var secret = "Global"; // Global variable declaration
function myFunction() {
secret = "Hello, world!"; // Global secret variable changed
console.log(secret); // "Hello, world!"
}
console.log(secret); // "Hello, world!"