【问题标题】:Using prototype to define a getter/setter使用原型定义 getter/setter
【发布时间】:2013-10-09 16:54:56
【问题描述】:

如果我有一个包含一堆 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);

【问题讨论】:

    标签: javascript getter-setter


    【解决方案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'];
        } 
    };
    

    【讨论】:

    • 但是arguments关键字会不会被“return function()”弄糊涂,认为没有从不任何参数?
    • 没有。返回的函数与任何其他函数一样,唯一的区别是它可以访问数据变量。闭包返回的是函数对象,而不是执行它。
    • 嗯。我收到 Uncaught TypeError: Cannot set property 'myFirstMethod' of undefined。我不明白这里需要 IIFE。
    • IIFE 创建了一个新的本地范围,这意味着在其中设置的变量不能在全局范围内访问。见benalman.com/news/2010/11/…
    猜你喜欢
    • 2012-05-22
    • 1970-01-01
    • 1970-01-01
    • 2023-03-12
    • 2014-01-04
    • 1970-01-01
    • 2011-03-14
    • 2020-08-16
    • 1970-01-01
    相关资源
    最近更新 更多