This is my code:
var emptyF开发者_运维知识库unction = function () {};
console.log(emptyFunction === function () {});
This will log false
in the console. Why?
Because the function expression, when executed, produces a new function object.
===
returns true only if the two operands are the same object.
From the spec (emphasis mine):
The production FunctionExpression : function ( FormalParameterListopt ) { FunctionBody } is evaluated as follows: 1. Return the result of creating a new Function object as specified in 13.2 with parameters specified by FormalParameterListopt and body specified by FunctionBody. Pass in the LexicalEnvironment of the running execution context as the Scope. Pass in true as the Strict flag if the FunctionExpression is contained in strict code or if its FunctionBody is strict code.
Because
function(){}
is an anonymous function "instance".
So you set emptyFunction to one instance of an anonymous function and then check to see if it "equals" another different instance. Just because the two anonymous functions you have defined are functionally equivalent does not mean they referentially equivalent i.e. they exist at different memory addresses. The same outcome (false) would be the result in any language.
it's because they are different instances of object so they wont be equal.
=== are used for same objects like checking a boolean variable if it is true or false.
Using ===
will check 2 things
- Object
- Equality
This way u can differentiate between 1/0 and true/false.
Which cant be done with ==
function(){}
is actually an error for one. Try it, open your console and just type:
function(){}
and press return. It should give you an error. This is because you need to set it as one of the following like:
function foo(){}
var foo = function(){}
(function(){})
It fails because they aren't the same at all.
精彩评论