判断一个函数是否是箭头函数最常用的方法是检查其是否有prototype属性,因为箭头函数没有prototype而常规函数有;具体可通过!fn.hasownproperty('prototype')来判断,1. 首先确认参数是函数类型,2. 然后检查其是否不具有prototype属性;该方法原理在于箭头函数不能作为构造函数使用,因此无prototype,而普通函数都有;局限性包括bind返回的函数可能影响判断、某些内置函数也可能无prototype,且该方法本质是间接推断而非直接标识;javascript未提供内置isarrowfunction方法,可能因语言设计更关注行为而非类型,且实际开发中更多应关心函数能否被调用或this指向;其他方法如tostring()检测"=>”或尝试new调用均不推荐,因受代码压缩、转译、副作用等问题影响;因此,基于prototype的判断仍是当前最稳定可靠的方式。

在JavaScript里,要直接判断一个函数是不是箭头函数,说实话,并没有一个内置的、像
Array.isArray()
prototype
对于大多数常规函数(包括使用
function
prototype
this
new
prototype
fn.prototype
undefined
prototype
这是一个挺有意思的设计选择,JavaScript 在函数类型上并没有像其他语言那样提供一个非常明确的
isArrowFunction
new
原理: 常规函数,无论是声明式还是表达式,它们都有一个
prototype
new
prototype
function RegularFunction() {}
const regularFnExpr = function() {};
console.log(typeof RegularFunction.prototype); // object
console.log(typeof regularFnExpr.prototype); // object而箭头函数,它们的设计初衷就是为了更简洁地定义函数,并且解决
this
this
new
prototype
const arrowFunction = () => {};
console.log(typeof arrowFunction.prototype); // undefined所以,你可以这样来判断:
function isArrowFunction(fn) {
if (typeof fn !== 'function') {
return false; // 不是函数,直接排除
}
// 检查是否没有 prototype 属性
return !fn.hasOwnProperty('prototype');
}
console.log(isArrowFunction(function() {})); // false
console.log(isArrowFunction(() => {})); // true
console.log(isArrowFunction(class MyClass {})); // false (类本身也是函数)
console.log(isArrowFunction(console.log)); // false (内置函数)局限性: 尽管
prototype
Function.prototype.bind
bind
prototype
prototype
prototype
prototype
prototype
isArrowFunction
这确实是个值得思考的问题。JavaScript 的设计哲学里,很多时候更倾向于关注对象的“行为”而非其“类型”。比如,我们判断一个对象是不是数组,通常用
Array.isArray()
length
箭头函数虽然在
this
this
当然,这只是我个人的一个猜测。也可能是因为在语言演进的过程中,添加一个这样的方法被认为是不必要的,或者说,现有的特性(比如
prototype
isArrowFunction
除了
prototype
Function.prototype.toString()
思路: 将函数转换为字符串,然后检查字符串中是否包含
=>
示例(仅供说明,不推荐使用):
function isArrowFunctionByString(fn) {
if (typeof fn !== 'function') {
return false;
}
// 检查函数字符串是否包含箭头语法
// 注意:这非常脆弱,会被代码压缩、转译等影响
return fn.toString().includes('=>');
}
console.log(isArrowFunctionByString(() => {})); // 通常为 true
console.log(isArrowFunctionByString(function() {})); // false问题:
=>
function
toString()
=>
尝试使用new
new
TypeError
new
try...catch
总的来说,在需要判断一个函数是否是箭头函数时,检查
fn.hasOwnProperty('prototype')new
this
prototype
以上就是js怎么判断函数是否是箭头函数的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号