简体   繁体   中英

Is it bad practice to re-assign a JavaScript function from within itself

Scenario

I have an object in JavaScript. This object contains a function which will execute either statementA or statementB based on a boolean property. The boolean property should be considered read only, and for arguments sake let's say it's set within the constructor.

Code

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

Question

Is it bad practice to re-assign a method from within the scope of itself? I've tried to do some research into it, but so far I've been unsuccessful.

It's the same, but more readable:

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

I think, pass callback to prototype go, and other prototype will check and create callback from 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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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