2

I have an object with a method, I want to pass the method as an argument to another function. However the function must know the object associated with the method (or it can't access values assigned to the object after creation).

Is there a way to this without resorting to passing the object/method as a string?
(ex not using: window[function_name];)

function My_Object(name){
    this.name = name;
}

My_Object.prototype.My_Method = function(){
     alert(this.name);
}

//This is the function that passes the method
function Runner(){
     var NewObject = new My_Object('Andre');
     test(NewObject.My_Method);//this is where it should break
}

//This is the function that receives and calls the Object's method
function test(func){
    func();
}
8
  • it would help if you paste some code that shows us what you want to accomplish Commented Sep 17, 2014 at 16:57
  • just pass the object itself to the function, the function can then access everything it needs. Some code samples would help give more context-specific answers. Commented Sep 17, 2014 at 16:57
  • 3
    This is totally a duplicate. My Google-fu is just letting me down. Commented Sep 17, 2014 at 16:58
  • 2
    test(function() { NewObject.My_Method(); }) ? Commented Sep 17, 2014 at 17:09
  • 3
    ... or test(NewObject.My_Method.bind(NewObject)); Commented Sep 17, 2014 at 17:11

2 Answers 2

2

Use a anonymous function:

//This is the function that passes the method
function Runner(){
     var NewObject = new My_Object('Andre');
     test(function() {
         NewObject.My_Method();
     });
}

or bind your method to NewObject like this:

//This is the function that passes the method
function Runner(){
     var NewObject = new My_Object('Andre');
     test(NewObject.My_Method.bind(NewObject));
}



And if you don't change your test function in the future, you can simple call the function you want to test in the Runner function:

//This is the function that passes the method
function Runner(){
     var NewObject = new My_Object('Andre');
     NewObject.My_Method(); // directly call the function
}
Sign up to request clarification or add additional context in comments.

Comments

1

The comment about execution context is important here:

//This is the function that passes the method
function Runner(){
     var NewObject = new My_Object('Andre');
     test(NewObject.My_Method,NewObject);
}

//This is the function that receives and calls the Object's method
function test(func,ctx){
    func.apply(ctx || this);
}

Comments

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.