I am exploring a pattern where you can save a global reference to the current instance for simple use in anonymous functions where the this
keyword is out of context. Consider this:
var instance;
var a = function(id) {
instance = this;
this.id = id;
};
a.prototype.get = function() {
return (function() {
return instance.id;
})();
};
var x = new a('x');
var y = new a('y');
console.log(x.get());
console.log(y.get());
This obviously won't work since instance is defined in the constructor, to each time .get()
is called, instance
will reference the last constructed object. So it yields 'y' both times.
However, I'm looking for a way to grab the instance inside a prototype method without using the this
keyword, to make the code more readable. Singletons is not an option here, I need the prototypal inheritance.