Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What are the interview questions about closures

2025-04-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article introduces the relevant knowledge of "what are the interview questions about closures". In the operation of actual cases, many people will encounter such a dilemma. Next, let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!

Every JavaScript programmer must know what a closure is. In a JavaScript interview, you are likely to be asked about the concept of closures.

Here are 7 challenging interview questions about JavaScript closures.

Don't look at the answers or run the code to see how good you are. It will take about half an hour to finish these problems.

1. Warm up

There are the following functions clickHandler,immediate and delayedReload:

Let countClicks = 0; button.addEventListener ('click', function clickHandler () {countClicks++;}); const result = (function immediate (number) {const message = `number is: ${number} `; return message;}) (100); setTimeout (function delayedReload () {location.reload ();}, 1000)

Which of these three functions can access external scope variables?

Answer:

ClickHandler can access the variable countClicks from an external scope.

Immediate cannot access any variables in the external scope.

DelayedReload accesses the global variable location from the global scope (that is, the outermost scope).

two。 Missing parameter

What does the following code output:

(function immediateA (a) {return (function immediateB (b) {console.log (a); / / = >?}) (1);}) (0)

Answer:

The output is: 0

Call immediateA with the argument 0, so the a parameter is 0.

The immediateB function, which is nested in the immediateA function, is a closure that gets the variable a from the external immediateA scope, where an is 0. So the output of console.log (a) is 0.

3. Who's who

What will the following code output?

Let count = 0; (function immediate () {if (count = 0) {let count = 1; console.log (count); / / output what? } console.log (count); / / output what? ) ()

Answer:

Output 1 and 0

The first statement, let count = 0, declares a variable count.

Immediate () is a closure that gets the count variable from the external scope. Within the scope of the immediate () function, count is 0.

However, within the condition, another let count = 1 declares the local variable count, which overrides the count outside the scope. The first console.log (count) outputs 1.

The second console.log (count) output is 0 because the count variable here is accessed from an external scope.

4. Tricky closure

What does the following code output:

For (var I = 0; I

< 3; i++) { setTimeout(function log() { console.log(i); // =>

?, 1000);}

Answer output:

3, 3, 3 .

The code is executed in two phases.

Phase 1:

For () is repeated 3 times. In each loop, a new function log () is created, which will capture the variable I. SetTimout () arranges that log () be executed after 1000 milliseconds.

When the for () loop is complete, the variable I has a value of 3.

Phase 2:

The second phase occurs after 1000ms:

SetTimeout () executes the predetermined log () function. Log () reads the current value of variable I 3 and outputs 3

So output 3, 3, 3.

5. The wrong message

What will the following code output:

Function createIncrement () {let count = 0; function increment () {count++;} let message = `Count is ${count} `; function log () {console.log (message);} return [increment, log];} const [increment, log] = createIncrement (); increment (); log (); / / = >?

Answer:

Output: 'Count is 0'

The increment () function is called three times, increasing the count to 3.

The message variable exists in the scope of the createIncrement () function. Its initial value is' Count is 0'. But even though the count variable has been incremented several times, the value of the message variable is always' Count is 0'.

The log () function is a closure that gets the message variable from the scope of createIncrement (). Console.log (message) outputs' Count is 0' to the console.

6. Re-encapsulation

The following function createStack () is used to create the stack structure:

Function createStack () {return {items: [], push (item) {this.items.push (item);}, pop () {return this.items.pop ();}};} const stack = createStack (); stack.push (10); stack.push (5); stack.pop (); / / = > 5 stack.items; / / = > [10] stack.items = [10,100,100] / / the package of the stack structure has been destroyed.

It works fine, but with one small problem, because the stack.items property is exposed, anyone can modify the items array directly.

This is a big problem because it breaks the stack encapsulation: only the push () and pop () methods should be public, while stack.items or any other details cannot be accessed.

Refactoring the stack implementation above using the concept of closures makes it impossible to access the items array outside the scope of the createStack () function:

Function createStack () {/ / write your code here} const stack = createStack (); stack.push (10); stack.push (5); stack.pop (); / / = > 5 stack.items; / / = > undefined

Answer:

The following is the refactoring of createStack ():

Function createStack () {const items = []; return {push (item) {items.push (item);}, pop () {return items.pop ();}};} const stack = createStack (); stack.push (10); stack.push (5); stack.pop (); / / = > 5 stack.items; / / = > undefined

Items has been moved to the createStack () scope.

After this modification, the items array cannot be accessed or modified from outside the createStack () scope. Now items is a private variable and the stack is encapsulated: only the push () and pop () methods are public.

The push () and pop () methods are closures, and they get items variables from the scope of the createStack () function.

7. Intelligent multiplication

Write a function multiply () that multiplies two numbers:

Function multiply (num1, num2) {/ / write your code here.}

Request:

If multiply (num1,numb2) is called with two parameters, the product of the two parameters should be returned.

But if called with one argument, the function should return another function: const anotherFunc = multiply (num1). The returned function performs multiplication num1 * num2 when calling anotherFunc (num2).

Multiply (4,5); / / = > 20 multiply (3,3); / / = > 9 const double = multiply (2); double (5); / / = > 10 double (11); / / = > 22

Answer:

Here is one way to implement the multiply () function:

Function multiply (number1, number2) {if (number2! = = undefined) {return number1 * number2;} return function doMultiply (number2) {return number1 * number2;};} multiply (4,5); / / = > 20 multiply (3,3); / / = > 9 const double = multiply (2); double (5); / / = > 10 double (11); / / = > 22

If the number2 parameter is not undefined, the function only returns number1 * number2.

However, if number2 is undefined, it means that the multiply () function has been called with one parameter. At this point, you will return a function doMultiply (), which will perform the actual multiplication when called later.

DoMultiply () is a closure because it gets the number1 variable from the scope of multiply ().

This is the end of the content of "what are the interview questions about closures". Thank you for reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report