简体   繁体   English

在闭包范围中设置变量

[英]Setting a variable in the closure scope

I think I understand why variables exist outside of the function they were declared in, because you're returning another function: 我想我理解为什么变量存在于它们声明的函数之外,因为你正在返回另一个函数:

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'

The way that it's written now, calling A() is like a getter. 它现在写的方式,调用A()就像一个getter。

Q: How can I write myFunction so that calling A(123) is a setter? 问:如何编写myFunction以便调用A(123)是一个setter?

Try the following: 请尝试以下方法:

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'

You could do something like this if you want both getter and setter for example: 如果你想要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"

Should be as simple as: 应该如此简单:

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;
        }
    }
}

Since the closure variable is within the closure of the function's scope, you should be able to assign to it the same way you can read from it. 由于closure变量在函数范围的闭包内,因此您应该能够以与它相同的方式分配它。

See jsFiddle: http://jsfiddle.net/WF4VT/1/ 见jsFiddle: http//jsfiddle.net/WF4VT/1/

Another alternative would be to use a class and define getters and setters: 另一种方法是使用类并定义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);

Demo: http://jsfiddle.net/louisbros/bMkbE/ 演示: http//jsfiddle.net/louisbros/bMkbE/

jsFiddle Demo jsFiddle演示

Have your returned function accept an argument. 让您返回的函数接受参数。 Use it as a setter: 将它用作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'

Revisiting this question, I see that I could do it this way: 重新审视这个问题,我发现我可以这样做:

  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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM