0
const info = {
  name: 'Steve',
  phone: 20655564,
  email: '[email protected]',
  sayName: function(){
    console.log('Hello I am ' + info.name);
  },
};

I made a random object and was using a different function to call that objects method.

function invokeMethod(object, method) {
  // method is a string that contains the name of a method on the object
  // invoke this method
  // nothing needs to be returned
  const func = object[method]
  object.func();

}

invokeMethod(info, 'sayName');

However, when I when I run the invokeMethod function above I get the error func is not a function. However, when I run

return func

as a test I get [function]

trying to figure out how to get it to do the sayName method

2
  • why can't you pass in the function instead of the object and method name? Commented Mar 18, 2018 at 2:58
  • object[method](); or func.call(object); Commented Mar 18, 2018 at 2:59

1 Answer 1

4

There is a error at line object.func();

It should be func.call(object); instead of object.func(); Or you should call it directly object[method]()

const info = {
  name: 'Steve',
  phone: 20655564,
  email: '[email protected]',
  sayName: function(){
    console.log('Hello I am ' + info.name);
  },
};


function invokeMethod(object, method) {
  // method is a string that contains the name of a method on the object
  // invoke this method
  // nothing needs to be returned
  const func = object[method]
  func.call(object);

}

invokeMethod(info, 'sayName');

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

1 Comment

this messes up this in the inner function if it is not explicitly bound. It's better to do object[method]();, or maybe func.call(object);.

Your Answer

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