11

Can't figure out how to pass object's method as a parameter properly.

Here is my code:

var MyTest = function (p1) {
  this.p1 = p1;
};
MyTest.prototype.getParam = function () {
  return this.p1;
};

function doAction(getParamCallback) {
  console.log(getParamCallback());
}

var mt = new MyTest(123);
console.log(mt.getParam()); // 123
doAction(mt.getParam);      // undefined

The only way to pass a method correctly I have found is to pass both object and method and use call():

function doAction2(obj, getParamCallback) {
  console.log(getParamCallback.call(obj));
}
doAction2(mt, mt.getParam);    // 123

Is there any way that requires only method to be passed, not both method and object?

1 Answer 1

13

You need to pass the this context as well. In provided example, methos is being called in the context of window, and window does not have property p1

Use .bind() to pass the context. bind returns a function that when later executed will have the correct context set for calling the original function. This way you can maintain context in async callbacks, and events.[Reference]

Try this:

var MyTest = function(p1) {
  this.p1 = p1;
};
MyTest.prototype.getParam = function() {
  return this.p1;
};

function doAction(getParamCallback) {
  alert(getParamCallback());
}

var mt = new MyTest(123);

doAction(mt.getParam.bind(mt));

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

1 Comment

Thanks Rayon! This works perfectly in Google Apps Script as well!

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.