Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Wrong to have a function change the variable reference it was called from?

JavaScript has all amounts of crazy flexibility. I decided to take advantage of it and have a function change itself on the first call. Is this a bad thing to do? It works like this:

(function(){
   var nextAfter = function(){};
   Something.prototype.next = function(){
      //do pre-start actions.
      this.next = nextAfter;
   };
})();

This function is called inside of a main loop, so it gets called many times, but the instance is only ever "supposed" to be instantiated once.

like image 293
Andrew Avatar asked Jul 08 '15 18:07

Andrew


1 Answers

It is a perfectly reasonable thing to do.

For example, It can be a useful way of implementing state changes in a state machine, but I'm sure that you could find many other uses.

You may also want to look into how to implement the same functionality with closures -- it may be cleaner depending on the use case.

Edit; example of a closure which doesn't change the prototype

Something = (function(){
    var next = function() { next = nextAfter; console.log("A"); }
    var nextAfter = function() { console.log("B"); }

    return {
        next: function(){ next(); }
    }
})();

The benefit of the closure is that you don't change the global prototype function for that object type, and you can now have multiple independent object where each closure object can keep their own state.

like image 90
Soren Avatar answered Nov 15 '22 00:11

Soren