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"]();
1

1 Answer 1

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"]()

Sign up to request clarification or add additional context in comments.

2 Comments

+1 Rather than "attached to" you might say "called as a method of".
@RobG - Yea good call, I put it in quotes because I couldn't think of a good way to phrase it..

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.