0

如果我有一个包含一堆 getter 和 setter 的应用程序,那么我认为我需要使用闭包来保持 setter 的值,不是吗?

这是我到目前为止所得到的,但我认为这两种方法应该是返回函数(闭包)。我认为我不应该使用 this.local.result 因为两者会发生冲突。

myApplication = function(){
    this.local = {};  
};
myApplication.prototype.myFirstMethod = function(){
    if (arguments.length) {
        this.local.result = arguments[0];
    } else {
        return this.local.result;
    } 
};
myApplication.prototype.mySecondMethod = function(){
    if (arguments.length) {
        this.local.result = arguments[0];
    } else {
        return this.local.result;
    } 
};

var app = new myApplication();
app.myFirstMethod(1);
result = app.myFirstMethod();

console.log(result);
4

1 回答 1

1

使用闭包的目的是保持变量私有(不能从全局范围直接访问)。

以下是如何使用闭包:

myApplication.prototype.myFirstMethod = (function () {
    var data = '';
    return function () {
        if (arguments.length) {
            data = arguments[0];
        } else {
            return data;
        }
    }
})();

如果您不需要数据是私有的,您可以简单地执行以下操作:

myApplication.prototype.myFirstMethod = function(){
    if (arguments.length) {
        this.local['firstData'] = arguments[0];
    } else {
        return this.local['firstData'];
    } 
};
于 2013-10-09T17:14:50.163 回答