Phi*_*enn 4 javascript closures
我想我理解为什么变量存在于它们声明的函数之外,因为你正在返回另一个函数:
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'
Run Code Online (Sandbox Code Playgroud)
它现在写的方式,调用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'
Run Code Online (Sandbox Code Playgroud)