[英]Setting a variable in the closure scope
我想我理解為什么變量存在於它們聲明的函數之外,因為你正在返回另一個函數:
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'
如果你想要getter和setter,你可以這樣做:
var func = function() {
var closure = 'foo';
return {
get: function() { return closure; },
set: function(value) { closure = value; }
}
};
var A = func();
A.set('foobar');
console.log(A.get()); //=> "foobar"
應該如此簡單:
myFunction = function() {
var closure = 'closure scope'
return function(setTo) {
if (typeof setTo !== "undefined") {
closure = setTo;
return this; //support call chaining, good idea hek2mgl
} else {
return closure;
}
}
}
由於closure
變量在函數范圍的閉包內,因此您應該能夠以與它相同的方式分配它。
見jsFiddle: http : //jsfiddle.net/WF4VT/1/
另一種方法是使用類並定義getter和setter:
function MyClass(p){
this._prop = p;
}
MyClass.prototype = {
constructor: MyClass,
get prop(){
return this._prop;
},
set prop(p){
this._prop = p;
}
}
var myObject = new MyClass("TEST");
console.log(myObject.prop);
myObject.prop = "test";
console.log(myObject.prop);
讓您返回的函數接受參數。 將它用作setter:
myFunction = function() {
var closure = 'closure scope';
return function(val) {
closure = val;
return closure;
}
}
A = myFunction(); // myFunction returns a function, not a value
B = A(123); // A is a function, which when run, returns:
console.log(B); // 'closure scope'
重新審視這個問題,我發現我可以這樣做:
function outside() { var result = 'initialized' return inside function inside(argVariable) { if(arguments.length) { result = argVariable return this } else { return result } } } myFunction = outside() // outside returns a function X = myFunction() // returns: 'initialized' $('body').append(X + '<br>') myFunction(123) // setter X = myFunction() // returns: 123 $('body').append(X)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.