You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JS中对象(含函数)严格相等比较的实现机制探究

Understanding Strict Equality (===) 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 to a.
  • When you declare b = function(){}, it creates a second, entirely separate function object (even though the function body is identical to a’s). So a and b point to different memory locations, hence a === b returns false.
  • When you set c = a, you’re not creating a new function—you’re just copying the reference stored in a to c. Now both a and c point to the same function object in memory, so a === c returns true.

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 09:29:45