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?
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(); }
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With