3

I am trying to store function pointers of an object's functions in an array.But it's giving me problems when I want to access another property of the object within the function.Could any one solve this or give me an idea how to work around it?

function O(){
      this.name="hello";
      this.f=function(){
        alert(this.name);//why does "this" refer to the array arr rather than the object?
      };
      this.arr=[];
       this.arr["x"]=this.f;



    }
    var d=new O();
    d.arr["x"]();
  • See my explanation of how "this" works: http://stackoverflow.com/questions/13441307/how-does-the-this-keyword-in-javascript-act-within-an-object-literal/13441628#13441628 – slebetman May 21 '13 at 04:21

1 Answers1

4

In this case, this will reference the object that the function was called as a method of (in your case, the array). You'll want to store a reference to the O function somewhere within the scope, such as:

function O(){
      var self = this;
      this.name="hello";
      this.f=function(){
        alert(self.name);//why does "this" refer to the array arr rather than the object?
      };
      this.arr=[];
       this.arr["x"]=this.f;



    }
    var d=new O();
    d.arr["x"]();

This is a pretty common pattern in JavaScript, and has the added benefit of allowing the function to execute the same way, whether it was called through d.f() or d.arr["X"]()

Mike Christensen
  • 88,082
  • 50
  • 208
  • 326