javascript - 如何在 Javscript 中优雅地实现PHP中的 call_user_func() 函数
本文介绍了javascript - 如何在 Javscript 中优雅地实现PHP中的 call_user_func() 函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
问 题
如何在 Javascript
中优雅地实现PHP
中的 call_user_func()
函数.
解决方案
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
这篇关于javascript - 如何在 Javscript 中优雅地实现PHP中的 call_user_func() 函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文