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.
Edit: Since you’re avoiding to store “local instances”, there are some approaches, for example:
Using
callorapplyto change thethisvalue of the invoked function:Using an argument:
The new ECMAScript 5th Edition introduced the
bindmethod, which is extremely useful to persist thethisvalue and optional bound arguments, you can find a compatible implementation here: