在对象javascript上调用方法

时间:2018-03-18 02:57:07

标签: javascript object

const info = {
  name: 'Steve',
  phone: 20655564,
  email: 'SJ@yahoo.com',
  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]
  object.func();

}

invokeMethod(info, 'sayName');

但是,当我运行上面的invokeMethod函数时,我得到错误func不是函数。但是,当我跑

return func

作为我得到的测试 [function]

试图找出如何让它来做sayName方法

1 个答案:

答案 0 :(得分:3)

object.func();

时出错

应该是func.call(object);而不是object.func(); 或者您应该直接致电object[method]()

const info = {
  name: 'Steve',
  phone: 20655564,
  email: 'SJ@yahoo.com',
  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');