views:

36

answers:

1

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.

+1  A: 

Edit: Since you're avoiding to store "local instances", there are some approaches, for example:

Using call or apply to change the this value of the invoked function:

var a = function (id) {
  this.id = id;
};

a.prototype.get = function () {

  return (function() {
    return this.id; // the inner `this` value will refer to the value of outside
  }).call(this); 
};

Using an argument:

//..
a.prototype.get = function () {

  return (function(instance) {
    return instance.id;
  })(this); 
};

The new ECMAScript 5th Edition introduced the bind method, which is extremely useful to persist the this value and optional bound arguments, you can find a compatible implementation here:

//..
a.prototype.get = function() {
  var boundFunction = (function () {
    return this.id;
  }).bind(this);

  return boundFunction(); // no matter how the function is invoked its `this`
};                        // value will always refer to the instance.
CMS
yea, exactly. I'm looking for a way to avoid saving local instances for each prototype method when using anonymous functions.
David
I guess that's a "no", but thanks for providing patterns for bringing the context into anonymous functions.
David