扫码关注官方订阅号
如何在 Javascript 中优雅地实现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
微信扫码关注PHP中文网服务号
QQ扫码加入技术交流群
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
PHP学习
技术支持
返回顶部
欢迎选择我的课程,让我们一起见证您的进步~~