Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can an instance of a class replace itself in JavaScript?

Tags:

javascript

I have a variable in a global scope which is assigned an instance of a class like this:

window.someInstance = new MyClass();

At some point later, I need to replace that variable with a new instance, but is it possible/acceptable to do that from within a method of the class itself? For example:

function MyClass () {

    this.myClassMethod = function () {
        window.someInstance = new MyClass();
    };

}

window.someInstance = new MyClass();
window.someInstance.myClassMethod.call();

An odd scenario I know but it works cleanly, I'm just not sure if this creates any memory or referencing issues?

like image 587
Russ Back Avatar asked Dec 19 '11 11:12

Russ Back


1 Answers

Only if everyone always accessess the instance indirectly via window.somereference. As soon as anyone does var x = window.someinstance then you lose the indirection and your trick would stop working.

You might acheieve a more robust implementation by placing the indirection in a variable of the instance itself instead of in a global variable

function Instance(){
   this.impl = ...;
}
Instance.prototype = {
    changeImpl: function(){ this.impl = new Impl(); },

    //delegate all other methods
    f1: function(){ return this.impl.f1(); }
}
like image 127
hugomg Avatar answered Sep 23 '22 18:09

hugomg