如何判断JavaScript中两个函数是否源自同一定义(含闭包场景)
判断闭包中生成的函数是否源自同一函数定义
注意:本问题聚焦于判断两个函数是否源自同一函数定义,而非JavaScript中一般对象(如数组、日期)的比较。
示例代码:
function father(num) { function generateChild() { console.log(num); } return generateChild; } const child1 = father(1); const child2 = father(2); // 测试: console.log(child1 == child2); // false console.log(child1 === child2); // false(符合预期) console.log(child1.prototype === child2.prototype); // false console.log(child1.prototype.constructor === child2.constructor.prototype); // false console.log(Object.getOwnPropertyDescriptor(child1.prototype, 'constructor').value === Object.getOwnPropertyDescriptor(child2.prototype, 'constructor').value); // false console.log(child1.toString() == child2.toString()); // true.
如何判断child1和child2是同一个generateChild函数?
虽然toString()方法能得到匹配结果,但不适合使用——因为两个在不同位置定义、代码完全相同的函数,toString()的返回值也会一致,但它们并非源自同一定义。例如:
function test1(){console.log('test')} function test2(){console.log('test')}
test1.toString() === test2.toString()结果为true,但它们并不是像generateChild那样从同一个函数定义实例化出来的。
需要注意的是,由于目标函数定义在另一个函数内部、运行在闭包环境中,情况更为复杂。像Array.prototype.map === Array.prototype.map这类简单的函数全等比较方法完全不适用。
另外,浏览器开发者工具能识别这类函数源自同一位置的构造函数,构造函数似乎存在[[FunctionLocation]]属性,但该属性无法在代码运行时访问。
与其他相关问题的区别
- 诸如《How can I determine equality for two JavaScript objects?》这类问题聚焦于普通对象的比较(比如判断
{a:1} == {a:1}或[1,2] == [1,2]),这类场景可通过键值对比、遍历属性值实现,但函数无法套用这类逻辑。 - 本问题与《Javascript comparing if 2 functions are exact same》虽相似,但核心差异在于:本问题中的函数是定义在另一个函数内部的闭包函数。
内容的提问来源于stack exchange,提问作者academo
相关产品推荐
相关产品推荐

