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方法
答案 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');