在闭包范围中设置变量 [英] Setting a variable in the closure scope

查看:110
本文介绍了在闭包范围中设置变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想我知道为什么变量存在于它们声明的函数之外,因为你要返回另一个函数:

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'

现在写的方法是调用A 。

The way that it's written now, calling A() is like a getter.

问:我如何编写myFunction以便调用A(123)是一个setter?

Q: How can I write myFunction so that calling A(123) is a 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'

这篇关于在闭包范围中设置变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆