如何在 Javscript 中优雅地实现PHP中的 call_user_func() 函数

如何在 Javascript 中优雅地实现PHP中的 call_user_func() 函数.

阅读 3.3k
1 个回答

var a = 0

function increment(){
  a++
}

// 给你稍微扩展了一下,这个函数有两种调用方式
// 第一种是直接传函数名称,第二种是传函数本身
// 建议使用第二种方式
function call_user_func(fn){
   if(!fn) return;
   var type = typeof fn
   var args = Array.prototype.slice.call(arguments, 1)
   if(type === 'function'){
     return fn.apply(this, args)
   }else if(type === 'string'){
     return this[fn].apply(this, args)
   }
}

// 传函数名称
call_user_func('increment', a)
console.log(a); // 1

// 传函数本身,建议使用这种方式
call_user_func(increment, a)
console.log(a); // 2
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题