JS中对象(含函数)严格相等比较的实现机制探究
===) for Functions in JavaScript Great question! Let’s break down exactly what’s happening here, and how it aligns with ECMAScript rules.
Core Rule for Strict Equality with Objects (Including Functions)
In JavaScript, functions are a type of object. When using the strict equality operator (===) to compare two objects (or functions), the comparison only returns true if both values reference the exact same object instance in memory. This is very similar to how Java compares object references—you’re checking if two variables point to the same "location" in memory, not if their content is identical.
Breaking Down Your Code
Let’s walk through your example step by step:
var a = function(){} var b = function(){} var c = a; console.log(a === b); // Logs false console.log(a === c); // Logs true
- When you declare
a = function(){}, JavaScript creates a new function object in memory and assigns its reference toa. - When you declare
b = function(){}, it creates a second, entirely separate function object (even though the function body is identical toa’s). Soaandbpoint to different memory locations, hencea === breturnsfalse. - When you set
c = a, you’re not creating a new function—you’re just copying the reference stored inatoc. Now bothaandcpoint to the same function object in memory, soa === creturnstrue.
Alignment with ECMAScript 5.1 Spec
As you referenced in your research, the ECMAScript 5.1 specification defines strict equality comparison such that for two object values, the result is true if and only if the values refer to the same object. There’s no conversion of functions to strings or other types here—strict equality skips type conversion entirely (unlike loose equality ==), and for objects, it’s purely a reference check.
Quick Note on Loose Equality (==)
Just to clarify: even if you used the loose equality operator (==) here, the result would be the same. For objects, both == and === use reference comparison—loose equality only differs from strict equality when comparing values of different types.
内容的提问来源于stack exchange,提问作者Alexander Mills

