从内部重新分配JavaScript函数是不好的做法

时间:2015-07-02 09:30:44

标签: javascript

方案

我在JavaScript中有一个对象。此对象包含一个函数,该函数将基于statementA属性执行statementBbooleanboolean属性应该被认为是只读的,为了论证,我们可以说它是在构造函数中设置的。

代码

var MyClass = function(flag) {
    this.flag = flag; // this will never change after here
}

MyClass.prototype.go = function() {
    if (this.flag) {
        this.go = function() {
            // statement a (true)
        };
    } else {
        this.go = function() {
            // statement b (false)
        }
    }

    this.go();
}

JS Bin demo

问题

从自身范围内重新分配方法是不好的做法吗?我试图对它进行一些研究,但到目前为止我还没有成功。

2 个答案:

答案 0 :(得分:2)

它是相同的,但更具可读性:

var MyClass = function (flag) {
    this.flag = flag; // this will never change after here
    this.go = flag ? function () {
        // statement a (true)
    } : function () {
        // statement b (false)
    };
}

答案 1 :(得分:0)

我认为,将回调传递给原型go,其他原型将检查并从flag创建回调。

var MyClass = function(flag) {
    this.flag = flag; // this will never change after here
}

MyClass.prototype.go = function(cb) {
    // todo: your code
    cb();
}

MyClass.prototype.createCallbackForGo = function() {
    if(this.flag) {
        this.go(function() {
            alert('this is true');
        });        
    } else {
        this.go(function() {
            alert('this is false');
        });
    }
}

var classTrue = new MyClass(true);
classTrue.createCallbackForGo();

var classFalse = new MyClass(false);
classFalse.createCallbackForGo();
相关问题