我想我明白为什么变量存在于它们声明的函数之外,因为你正在返回另一个函数:
myFunction = function() {
var closure = 'closure scope'
return function() {
return closure;
}
}
A = myFunction(); // myFunction returns a function, not a value
B = A(); // A is a function, which when run, returns:
console.log(B); // 'closure scope'
按照现在的写法,调用 A() 就像一个 getter。
问:如何编写 myFunction 以便调用 A(123) 是一个 setter?
最佳答案
尝试以下操作:
myFunction = function() {
var closure = 'closure scope'
// value is optional
return function(value) {
// if it will be omitted
if(arguments.length == 0) {
// the method is a getter
return closure;
} else {
// otherwise a setter
closure = value;
// with fluid interface ;)
return this;
}
}
}
A = myFunction(); // myFunction returns a function, not a value
A(123); // set value
B = A(); // A is a function, which when run, returns:
console.log(B); // '123'
关于javascript - 在闭包作用域中设置变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15735821/