Home  >  Article  >  Web Front-end  >  JavaScript closure interview questions that many programmers do wrong

JavaScript closure interview questions that many programmers do wrong

黄舟
黄舟Original
2017-03-10 14:28:381229browse

Interview questions evolved from work

This is a question I encountered at work. It seemed very interesting, so I treated it as a question for the interview and found that Almost no one can answer them all correctly and tell the reasons, so let’s talk about them.

Look at the question code first:

function fun(n,o) {
  console.log(o)
  return {
    fun:function(m){
      return fun(m,n);
    }
  };
}
var a = fun(0);  a.fun(1);  a.fun(2);  a.fun(3);//undefined,?,?,?
var b = fun(0).fun(1).fun(2).fun(3);//undefined,?,?,?
var c = fun(0).fun(1);  c.fun(2);  c.fun(3);//undefined,?,?,?
//问:三行a,b,c的输出分别是什么?

This is a very typical JS closure problem. There are three levels of fun functions nested in it. It is particularly important to figure out which fun function the fun function of each level is.

You can first write down the results you think on paper or other places, and then expand to see what the correct answer is?

//答案:
//a: undefined,0,0,0
//b: undefined,0,1,2
//c: undefined,0,1,1

Are you all correct? If you got all the answers right, congratulations. There is almost nothing that can stump you in the js closure question; if you don’t get the answer right, continue to analyze.

There are several functions in JS

First of all, what you need to understand before this is that functions in JS can be divided into two types, named functions (named functions) and anonymous functions.

The method of distinguishing these two functions is very simple. It can be judged by outputting fn.name. The one with a name is a named function, and the one without a name is an anonymous function.

Note: The name of the named function cannot be obtained on lower versions of IE, and undefined will be returned. It is recommended to test on Firefox or Google Chrome

or use the IE-compatible method of getting the function name to obtain the function name:

/**
    * 获取指定函数的函数名称(用于兼容IE)
    * @param {Function} fun 任意函数
    */
function getFunctionName(fun) {
    if (fun.name !== undefined)
        return fun.name;
    var ret = fun.toString();
    ret = ret.substr('function '.length);
    ret = ret.substr(0, ret.indexOf('('));
    return ret;
}

Then use the above function to test whether it is an anonymous function:

JavaScript closure interview questions that many programmers do wrong

You can know that the variable fn1 is a named function and fn2 is an anonymous function

Several ways to create functions

After talking about the types of functions, you also need to understand that there are several ways to create functions in JS.

1. Declare a function

The most common and standard way to declare a function, including function name and function body.


function fn1(){}


2. Create an anonymous function expression

Create a variable whose content is a function


var fn1=function (){}


Note that the function created using this method is an anonymous function, that is, there is no function name


var fn1=function (){};
getFunctionName(fn1).length;//0


3. Create a named function expression

Create a variable whose content is a function with a name


var fn1=function xxcanghai(){};


Note: The function name of the named function expression can only be used inside the creation function

That is, it is created using this method The function can only use fn1 in the outer layer of the function and cannot use the function name of xxcanghai. The naming of xxcanghai can only be used inside the created function

Test:

var fn1=function xxcanghai(){
    console.log("in:fn1<",typeof fn1,">xxcanghai:<",typeof xxcanghai,">");
};
console.log("out:fn1<",typeof fn1,">xxcanghai:<",typeof xxcanghai,">");
fn1();
//out:fn1< function >xxcanghai:< undefined >
//in:fn1< function >xxcanghai:< function >

You can see that the function name of xxcanghai cannot be used outside the function (out) and is undefined.

Note: Functions defined within an object such as var o={ fn : function (){…} } are also function expressions

4, Function constructor

You can pass a function string to the Function constructor and return a function containing this string command. This method creates an anonymous function.

JavaScript closure interview questions that many programmers do wrong

5. Self-executing functions


(function(){alert(1);})();
(function fn1(){alert(1);})();


Self-executing functions belong to the above "Function expression", the rules are the same

6. Other methods of creating functions

Of course there are other methods of creating functions or executing functions, which I won’t go into more here, such as using eval, SetTimeout, setInterval and other very common methods will not be introduced here. They are non-standard methods. We will not expand too much here.

What is the relationship between the three fun functions?

After talking about function types and methods of creating functions, we can return to the topic and look at this interview question.

There are three fun functions in this code, so the first step is to figure out the relationship between these three fun functions and which function is the same as which function.

function fun(n,o) {
  console.log(o)
  return {
    fun:function(m){
      //...
    }
  };
}

Let’s first look at the first fun function, which belongs to the standard named function declaration and is a newly created function. Its return value is an object literal expression and belongs to a new object.

This new object contains an attribute also called fun. From the above introduction, we can know that it is an anonymous function expression, that is, the attribute fun stores a newly created anonymous function expression.

Note: All declared anonymous functions are new functions.

So the first fun function and the second fun function are different, they are both newly created functions.

The problem of function scope chain

Before talking about the third fun function, we need to talk about whether the variable storing the current function can be accessed inside the function expression.

Test 1, function expression inside the object:


var o={
  fn:function (){
    console.log(fn);
  }
};
o.fn();//ERROR报错


JavaScript closure interview questions that many programmers do wrong

Test 2, function expression inside non-object:


var fn=function (){
  console.log(fn);
};
fn();//function (){console.log(fn);};正确


JavaScript closure interview questions that many programmers do wrong

结论是:使用var或是非对象内部的函数表达式内,可以访问到存放当前函数的变量;在对象内部的不能访问到。

原因也非常简单,因为函数作用域链的问题,采用var的是在外部创建了一个fn变量,函数内部当然可以在内部寻找不到fn后向上册作用域查找fn,而在创建对象内部时,因为没有在函数作用域内创建fn,所以无法访问。

所以综上所述,可以得知,最内层的return出去的fun函数不是第二层fun函数,是最外层的fun函数。

所以,三个fun函数的关系也理清楚了,第一个等于第三个,他们都不等于第二个。

到底在调用哪个函数?

再看下原题,现在知道了程序中有两个fun函数(第一个和第三个相同),遂接下来的问题是搞清楚,运行时他执行的是哪个fun函数?

function fun(n,o) {
  console.log(o)
  return {
    fun:function(m){
      return fun(m,n);
    }
  };
}
var a = fun(0);  a.fun(1);  a.fun(2);  a.fun(3);//undefined,?,?,?
var b = fun(0).fun(1).fun(2).fun(3);//undefined,?,?,?
var c = fun(0).fun(1);  c.fun(2);  c.fun(3);//undefined,?,?,?
//问:三行a,b,c的输出分别是什么?

1、第一行a


var a = fun(0);  a.fun(1);  a.fun(2);  a.fun(3);


可以得知,第一个fun(0)是在调用第一层fun函数。第二个fun(1)是在调用前一个fun的返回值的fun函数,所以:

第后面几个fun(1),fun(2),fun(3),函数都是在调用第二层fun函数。

遂:

在第一次调用fun(0)时,o为undefined;

第二次调用fun(1)时m为1,此时fun闭包了外层函数的n,也就是第一次调用的n=0,即m=1,n=0,并在内部调用第一层fun函数fun(1,0);所以o为0;

第三次调用fun(2)时m为2,但依然是调用a.fun,所以还是闭包了第一次调用时的n,所以内部调用第一层的fun(2,0);所以o为0

第四次同理;

即:最终答案为undefined,0,0,0

2、第二行b


var b = fun(0).fun(1).fun(2).fun(3);//undefined,?,?,?


先从fun(0)开始看,肯定是调用的第一层fun函数;而他的返回值是一个对象,所以第二个fun(1)调用的是第二层fun函数,后面几个也是调用的第二层fun函数。

遂:

在第一次调用第一层fun(0)时,o为undefined;

第二次调用 .fun(1)时m为1,此时fun闭包了外层函数的n,也就是第一次调用的n=0,即m=1,n=0,并在内部调用第一层fun函数fun(1,0);所以o为0;

第三次调用 .fun(2)时m为2,此时当前的fun函数不是第一次执行的返回对象,而是第二次执行的返回对象。而在第二次执行第一层fun函数时时(1,0)所以n=1,o=0,返回时闭包了第二次的n,遂在第三次调用第三层fun函数时m=2,n=1,即调用第一层fun函数fun(2,1),所以o为1;

第四次调用 .fun(3)时m为3,闭包了第三次调用的n,同理,最终调用第一层fun函数为fun(3,2);所以o为2;

即最终答案:undefined,0,1,2

3、第三行c


var c = fun(0).fun(1);  c.fun(2);  c.fun(3);//undefined,?,?,?


根据前面两个例子,可以得知:

fun(0)为执行第一层fun函数,.fun(1)执行的是fun(0)返回的第二层fun函数,这里语句结束,遂c存放的是fun(1)的返回值,而不是fun(0)的返回值,所以c中闭包的也是fun(1)第二次执行的n的值。c.fun(2)执行的是fun(1)返回的第二层fun函数,c.fun(3)执行的也是fun(1)返回的第二层fun函数。

遂:

在第一次调用第一层fun(0)时,o为undefined;

第二次调用 .fun(1)时m为1,此时fun闭包了外层函数的n,也就是第一次调用的n=0,即m=1,n=0,并在内部调用第一层fun函数fun(1,0);所以o为0;

第三次调用 .fun(2)时m为2,此时fun闭包的是第二次调用的n=1,即m=2,n=1,并在内部调用第一层fun函数fun(2,1);所以o为1;

第四次.fun(3)时同理,但依然是调用的第二次的返回值,遂最终调用第一层fun函数fun(3,1),所以o还为1

即最终答案:undefined,0,1,1

后话

这段代码原本是在做一个将异步回调改写为同步调用的组件时的代码,发现了这个坑,对JS的闭包有了更深入的了解。

关于什么是闭包,网上的文章数不胜数,但理解什么是闭包还是要在代码中自己去发现与领悟。

如果要我说什么是闭包,我认为,广义上的闭包就是指一个变量在他自身作用域外被使用了,就叫发生了闭包。

希望读者能通过本文对闭包现象有进一步的了解,如有其它见解或看法,欢迎指正或留言讨论。(完)

The above is the detailed content of JavaScript closure interview questions that many programmers do wrong. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn