具體思路:
利用Function.toString()方法,獲取到函數的源碼,再利用正則匹配獲取到參數名字。
實現代碼(代碼基於ES6):
// 獲取函數的參數名 function getParameterName(fn) { if(typeof fn !== 'object' && typeof fn !== 'function' ) return; const COMMENTS = /((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg; const DEFAULT_PARAMS = /=[^,)]+/mg; const FAT_ARROWS = /=>.*$/mg; let code = fn.prototype ? fn.prototype.constructor.toString() : fn.toString(); code = code .replace(COMMENTS, '') .replace(FAT_ARROWS, '') .replace(DEFAULT_PARAMS, ''); let result = code.slice(code.indexOf('(') + 1, code.indexOf(')')).match(/([^\s,]+)/g); return result === null ? [] :result; }
如有錯誤,請指正,感謝。
