admin管理员组

文章数量:1313346

Consider this piece of code:

var x = function z(){
    console.log("called x");
}

x(); // will print out "called x"
z(); // ReferenceError!

So, it is possible to store a named function inside a variable, but we still can only call the function by the variable name.

Is there any reason for this behavior? Why is it possible for us to store a named function inside a variable? Is there any other scenario where this might be useful?

Consider this piece of code:

var x = function z(){
    console.log("called x");
}

x(); // will print out "called x"
z(); // ReferenceError!

So, it is possible to store a named function inside a variable, but we still can only call the function by the variable name.

Is there any reason for this behavior? Why is it possible for us to store a named function inside a variable? Is there any other scenario where this might be useful?

Share Improve this question edited Jun 1, 2018 at 3:29 Sebastian Simon 19.5k8 gold badges61 silver badges84 bronze badges asked Aug 21, 2017 at 8:25 JackyefJackyef 5,01221 silver badges26 bronze badges 2
  • You can do the following: var z = function () { ... }; var x = z;. Then you can call both x() and z(). – Phylogenesis Commented Aug 21, 2017 at 8:28
  • 1 Hi, my purpose in asking this question isn't to find out how to make the call to z() works, but mainly to understand the reason for this particular behavior in javascript. @Phylogenesis – Jackyef Commented Aug 21, 2017 at 8:33
Add a ment  | 

2 Answers 2

Reset to default 9

When you use a named function expression (NFE) like that, the function's name is only in scope within the function:

var x = function z(){
    console.log(typeof z); // "function"
};
x();
console.log(typeof z);     // "undefined"

This is one of the big differences between a named function expression and a function declaration: An NFE doesn't add the function's name to the scope in which the expression appears; a declaration does add the function's name to the scope in which the declaration appears. (They also happen at different times, etc.; I do a rundown of the various ways of creating functions and how they work in this other answer.)

There are a couple of reasons for doing this:

  • It lets the function call itself (via its name) without relying on the variable, for situations where recursion is useful.

  • In ES5 and earlier, it gave you a way to give the function a name (for stack traces and similar). (In ES2015+, the function will have a name even if you use an anonymous expression is most cases; the name is set based on the expression.)

  • In ES2015+, it lets you give the function a different name from the one that would be inferred from the expression.

Just assigning the function z to the variable x like this:

function z () {
  console.log("called x");
}
var x = z;

x(); // will print out "called x"
z(); // will print out "called x"

本文标签: javascriptStoring named function in a variable with a different nameStack Overflow