js Functions change their meaning depending on the context .

function double(x){return x*2;}

This is a function declaration , It can also be a named function expression (named function expression), Depending on where it appears .

Declare a function , And bind a variable in the current scope .

The same function code can also be used as an expression .

var f=function double(x){return x*2;}

according to ECMAScript standard , The function is bound to a variable f, Not variables double. It's not necessary to name function expressions here , You can use anonymous function expressions directly .

var f=function(x){return x*2;}

The official difference between anonymous and named function expressions is that the latter is bound to the same variable as its function name , This variable will be a local variable in the function .

Can be used to write recursive function expressions

var f=function find(tree,key){

if(!tree){

return null;

}

if(tree.key === key){

return tree.value;

}

return find(tree.left,key)||find(tree.right,value);

}

Be careful : Variable find The scope of is only in its own function . Unlike function declarations , Named function expressions cannot be referenced externally through their internal function names .

find(myTree,”foo”);//error:find is not defined

Use It seems unnecessary to name function expressions for recursion , Because using the function name of the external scope can achieve the same effect

var f=function(tree,key){

if(!tree){

return null;

}

if(tree.key === key){

return tree.value;

}

return f(tree.left,key)||f(tree.right,value);

}

or

function find(tree,key){

if(!tree){

return null;

}

if(tree.key === key){

return tree.value;

}

return find(tree.left,key)||find(tree.right,value);

}

var f=find;

The real use of named functions is debugging

Most modern JS The environment provides for Error Stack tracking function for ten days . In stack tracing , The name of a function expression is usually used as its entry . The device debugger used to check the stack has a similar use of named function expressions .

Named function expressions are the source of scope and compatibility issues .ES Normative errors , stay ES3 It already exists ,JS The engine is required to represent the scope of a named function expression as an object , Like there's a problem with structure . The scope object contains only a single property , This property binds the function name to the function itself . The scope object also inherits Object.prototype Properties of . This means that just naming a function expression will also Object.prototype All properties in are referenced into the scope . It turns out that something goes wrong, like :

var constructor=function(){return null;};

var f=function f(){

return constructor();

};

f();//{}(in ES3 environments)

ES5 Fixed the problem . Run the following :

But some of the JS The environment still uses outdated object scopes , Some environments are even less up to standard , Using objects as scopes for anonymous function expressions .

The best way to avoid objects polluting the scope of a function expression in a system is to avoid it at any time Object.prototype Add attributes in , And avoid using any standards Object.prototype A local variable with the same property name .

In fashion JS Another flaw in the engine is the promotion of the declaration of named function expressions .

var f=function g(){return 17;}

g();//17( In a nonstandard environment )

Note that this is not standard behavior .

Somewhat JS The environment even f and g These two functions act as different objects , This leads to unnecessary memory allocation . A reasonable solution to this behavior is to create a local variable with the same name as the function expression and assign it to null.

var f=function g(){return 17;}

var g=null;

Even in an environment that does not mistakenly elevate function expression declarations , Use var Redeclare variables to ensure that variables are still bound g. Set a variable g by null Ensures that duplicate functions are garbage collected .

Reasonable conclusion

  • Naming function expressions can cause a lot of problems , So it's not worth using .
  • A less serious response is that the development phase uses named function expressions for debugging , Before publishing, build tools to convert all function expressions to anonymous .
  • Be clear about the platform you want to release JS Environmental Science .

Tips

  • stay Error Object and debugger use named function expressions to improve stack tracking
  • stay ES3 And the problem JS Environment , The scope of the function expression is Object.prototype Pollution
  • A hundred mistakes JS Named function expression declarations are promoted in the environment , And causes repeated storage of named function expressions
  • Consider avoiding using named function expressions or deleting function names before publishing
  • Make sure JS Code to correct implementation ES5 Environment , You don't have to worry about these problems anymore

[Effective JavaScript note ] The first 14 strip : Watch out for more articles on the clumsy scope of named function expressions

  1. [Effective JavaScript note ] The first 4 strip : Primitive types are better than closed objects

    js Yes 5 Two primitive value types : Boolean value . Numbers . character string .null and undefined. use typeof Check it out : typeof true; //"boolean" typeof 2; //&q ...

  2. [Effective JavaScript note ] The first 5 strip : Avoid using... For mixed types == Operator

    “1.0e0”=={valueOf:function(){return true;}} It's what it's worth ? These two completely different values use == Operators are equal . Why? ? Please have a look at <[Effective JavaSc ...

  3. [Effective JavaScript note ] The first 28 strip : Don't trust function objects toString Method

    js Functions have an extraordinary property , The ability to reproduce its source code as a string . (function(x){ return x+1 }).toString();//"function (x){ return x+ ...

  4. [Effective JavaScript note ] The first 27 strip : Use closures instead of strings to encapsulate code

    Function is a convenient way to store code as a data structure , The code can then be executed . This makes expressive higher-order functions abstract, such as map and forEach Make it possible . So is it js asynchronous I/O The core of the method . meanwhile , You can also represent the code as a string ...

  5. [Effective JavaScript note ] The first 3 Chapter : Using functions -- Personal summary

    Preface In this chapter, we will use , But I don't want to delve into the knowledge , Explain in detail . There is a lot of content in it 3 And so on , There's also a lot of talk about . But because of the length of the book itself , It's easy to ignore the corresponding small knowledge points . Many of the tips in this chapter are helpful , Especially in ...

  6. [Effective JavaScript note ] The first 15 strip : Beware of the clumsy scope of local block function declarations

    Nested function declaration . There is no standard way to declare functions in local blocks , But you can nest a function declaration at the top of another function . function f(){return "global"} function test(x) ...

  7. [Effective JavaScript note ] The first 6 strip : Understand the limitations of semicolon insertion

    Semicolons can be omitted js You can not force a semicolon at the end of a statement .( Suggest or add , If you don't add a semicolon, it's hard to find BUG) function Point(x,y){ this.x=x||0; this.y=y||0; } ...

  8. [Effective JavaScript note ] The first 11 strip : Mastering closures

    Understand the three basic facts of closure The first fact :js Allows you to refer to variables defined outside of the current function . function makeSandwich(){ var magicIngredient=”peanut butter”; ...

  9. [Effective JavaScript note ] The first 13 strip : Create a local scope using a function expression called immediately

    function wrapElements(a){ var res=[],i,n; for(i=0,n=a.length;i<n;i++){ res[i]=function(){return a ...

Random recommendation

  1. a Label fills the parent container

    body>div>a{Join} div{ width:150px; height:35px; } a{ display:block; line-height:35px; height:3 ...

  2. front end HTML standard

    HTML standard - The overall structure The document should be written in “<!DOCTYPE ......>” The first line starts with the top grid , Recommended “<!DOCTYPE html>”. The coding of the document must be stated charset, And with the file ...

  3. jquery.cookie Using document ,$.cookie() Documentation tutorial , js operation cookie Tutorial documentation .

    jquery.cookie Using document ,$.cookie() Documentation tutorial , js operation cookie Tutorial documentation . jquery.cookie The operation : jquery.cookie.js It's based on jquer ...

  4. jQuery.each Of function What are the parameters in ( It's understandable function Parameter problem in )

    1. No parameters $("img").each(function(){ $(this).toggleClass("example"); }); 1 2 3 2. There is one ...

  5. 【IBM】Merlin to Java Platforms bring non blocking I/O

    Merlin to Java Platforms bring non blocking I/O New features significantly reduce thread overhead Java Technology platforms are long overdue to provide non blocking I/O Mechanism . Fortunately, ,Merlin(JDK 1.4) One of them has been used on almost every occasion ...

  6. actual combat nginx Basic knowledge summary ( One )1.1

    squid Squid It's a cache Internet Data software , It receives users' download applications , And automatically process the downloaded data . When a user wants to download a home page , Can be directed to Squid Send out an application , want Squid Download instead , then S ...

  7. springMVC In a class Multiple methods in

    in front . It's already available SpringMVC A simple example is given , however , stay controller And we did that Controller Interface . In this way, we have to achieve handleRequest(HttpServletRequest ...

  8. MySQL( 11、 ... and ) The trigger

    The last article introduced a relatively simple view , In fact, it is relatively simple to use , What's more about view usage in the future , At that time, I will add . Next let's look at the use of triggers ! One . Trigger Overview 1.1. What is trigger trigger (Tri ...

  9. Java For special characters to do interval read processing (1.3.4)

    Read in the string first , And then use split Division , Note that when the default spacer has other meanings , Use \ Escape character escape The question is pat A problem of , Read in the main method to see the front on the line import java.util.Scanner; publi ...

  10. Python The actual battle of reptiles Requests+ Regular expression crawls cat's eye movie Top100

    import requests from requests.exceptions import RequestException import re import json # from multip ...