Table of Contents
1. Scope
Answer
2. Lost parameters
答案
7. 智能乘法
总结
Home Web Front-end JS Tutorial 7 interview questions about closures in JavaScript, can you answer them?

7 interview questions about closures in JavaScript, can you answer them?

Mar 26, 2021 am 09:41 AM
javascript Closure Interview questions

7 interview questions about closures in JavaScript, can you answer them?

Related recommendations: 2021 Big Front-End Interview Questions Summary (Collection)

Every JavaScript programmer must Know what a closure is. In a JavaScript interview, you will most likely be asked about the concept of closures.

The following are 7 more challenging interview questions about JavaScript closures.

Don't look at the answers or run the code to see how good you are. It takes about half an hour to complete these questions.

1. Scope

has 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);
Copy after login

Which of these 3 functions can access external scope variables?

Answer

  • clickHandler Ability to access the variable countClicks from the outer scope.

  • #immediate Cannot access any variables in the outer scope.

  • delayedReload Access global variables location from the global scope (that is, the outermost scope).

Recommended related tutorials: javascript video tutorial

2. Lost parameters

The following code What is output:

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

Answer

The output is: 0

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

immediateB The function nested in the immediateA function is a closure that gets a# from the outer immediateA scope ## Variable, where a is 0. Therefore the output of console.log(a) is 0.

3. Who is who

What will the following code output?

let count = 0;
(function immediate() {
  if (count === 0) {
    let count = 1;
    console.log(count); // 输出什么?
  }
  console.log(count); // 输出什么?
})();
Copy after login

Answer

Output

1 and 0

First statement

let count = 0 declares a variable count.

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

However, within the condition, another

let count = 1 declares a 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 the outer scope.

4. Tricky Closures

What does the following code output:

for (var i = 0; i < 3; i++) {
  setTimeout(function log() {
    console.log(i); // => ?
  }, 1000);
}
Copy after login

Answer

Output :

3

, 3, 3. The code is executed in two stages.

Phase 1

    for()
  1. Repeat 3 times. A new function log() will be created on each loop, which will capture the variable i. setTimout() Schedules log() to execute after 1000 milliseconds. When the
  2. for()
  3. loop completes, the value of variable i is 3.
Phase 2

The second phase occurs after 1000ms:

    setTimeout()
  1. Execution Scheduled log() function. log() Read the current value of variable i3, and output 3
  2. so output
3

, 3, 3.

5. Error 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(); 
increment(); 
increment(); 
log(); // => ?
Copy after login

Answer

Output:

'Count is 0'

increment()

The function is called 3 times, increasing count to 3.

message

The variable exists within 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 createIncrement() scope. console.log(message) Output log 'Count is 0' to the console.

6. Repackage

The following function

createStack()

is used to create the stack structure:<div class="code" style="position:relative; padding:0px; margin:0px;"><pre class="brush:php;toolbar:false">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(); // =&gt; 5 stack.items; // =&gt; [10] stack.items = [10, 100, 1000]; // 栈结构的封装被破坏了</pre><div class="contentsignin">Copy after login</div></div>It works fine Works, but has a small problem, since the

stack.items

property is exposed, anyone can modify the items array directly. This is a big problem because it breaks the encapsulation of the stack: only the

push()

and pop() methods should be public, and Neither stack.items nor any other details can be accessed. <p>使用闭包的概念重构上面的栈实现,这样就无法在 <code>createStack() 函数作用域之外访问 items 数组:

function createStack() {
  // 把你的代码写在这里
}

const stack = createStack();
stack.push(10);
stack.push(5);
stack.pop(); // => 5

stack.items; // => undefined
Copy after login

答案

以下是对 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
Copy after login

items 已被移至 createStack() 作用域内。

这样修改后,从 createStack() 作用域的外部无法访问或修改 items 数组。现在 items 是一个私有变量,并且栈被封装:只有 push()pop() 方法是公共的。

push()pop() 方法是闭包,它们从 createStack() 函数作用域中得到 items 变量。

7. 智能乘法

编写一个函数  multiply() ,将两个数字相乘:

function multiply(num1, num2) {
  // 把你的代码写在这里...
}
Copy after login

要求:

如果用 2 个参数调用 multiply(num1,numb2),则应返回这 2 个参数的乘积。

但是如果用 1个参数调用,则该函数应返回另一个函数: const anotherFunc = multiply(num1) 。返回的函数在调用 anotherFunc(num2)  时执行乘法  num1 * num2

multiply(4, 5); // => 20
multiply(3, 3); // => 9

const double = multiply(2);
double(5);  // => 10
double(11); // => 22
Copy after login

答案

以下是  multiply()  函数的一种实现方式:

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
Copy after login

如果 number2 参数不是 undefined,则该函数仅返回 number1 * number2

但是,如果 number2undefined,则意味着已经使用一个参数调用了 multiply() 函数。这时就要返回一个函数 doMultiply(),该函数稍后被调用时将执行实际的乘法运算。

doMultiply() 是闭包,因为它从 multiply() 作用域中得到了number1 变量。

总结

如果你答对了 5 个以上,说明对闭包掌握的很好。如果你答对了不到 5 个,则需要好好的复习一下了。

原文地址:https://dmitripavlutin.com/simple-explanation-of-javascript-closures/

转载地址:https://segmentfault.com/a/1190000039366748

更多编程相关知识,请访问:编程视频!!

The above is the detailed content of 7 interview questions about closures in JavaScript, can you answer them?. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1668
14
PHP Tutorial
1273
29
C# Tutorial
1255
24
What is the meaning of closure in C++ lambda expression? What is the meaning of closure in C++ lambda expression? Apr 17, 2024 pm 06:15 PM

In C++, a closure is a lambda expression that can access external variables. To create a closure, capture the outer variable in the lambda expression. Closures provide advantages such as reusability, information hiding, and delayed evaluation. They are useful in real-world situations such as event handlers, where the closure can still access the outer variables even if they are destroyed.

What are the advantages and disadvantages of closures in C++ functions? What are the advantages and disadvantages of closures in C++ functions? Apr 25, 2024 pm 01:33 PM

A closure is a nested function that can access variables in the scope of the outer function. Its advantages include data encapsulation, state retention, and flexibility. Disadvantages include memory consumption, performance impact, and debugging complexity. Additionally, closures can create anonymous functions and pass them to other functions as callbacks or arguments.

Solve the memory leak problem caused by closures Solve the memory leak problem caused by closures Feb 18, 2024 pm 03:20 PM

Title: Memory leaks caused by closures and solutions Introduction: Closures are a very common concept in JavaScript, which allow internal functions to access variables of external functions. However, closures can cause memory leaks if used incorrectly. This article will explore the memory leak problem caused by closures and provide solutions and specific code examples. 1. Memory leaks caused by closures The characteristic of closures is that internal functions can access variables of external functions, which means that variables referenced in closures will not be garbage collected. If used improperly,

How to implement closure in C++ Lambda expression? How to implement closure in C++ Lambda expression? Jun 01, 2024 pm 05:50 PM

C++ Lambda expressions support closures, which save function scope variables and make them accessible to functions. The syntax is [capture-list](parameters)->return-type{function-body}. capture-list defines the variables to capture. You can use [=] to capture all local variables by value, [&] to capture all local variables by reference, or [variable1, variable2,...] to capture specific variables. Lambda expressions can only access captured variables but cannot modify the original value.

Chained calls and closures of PHP functions Chained calls and closures of PHP functions Apr 13, 2024 am 11:18 AM

Yes, code simplicity and readability can be optimized through chained calls and closures: chained calls link function calls into a fluent interface. Closures create reusable blocks of code and access variables outside functions.

The impact of function pointers and closures on Golang performance The impact of function pointers and closures on Golang performance Apr 15, 2024 am 10:36 AM

The impact of function pointers and closures on Go performance is as follows: Function pointers: Slightly slower than direct calls, but improves readability and reusability. Closures: Typically slower, but encapsulate data and behavior. Practical case: Function pointers can optimize sorting algorithms, and closures can create event handlers, but they will bring performance losses.

The role of golang function closure in testing The role of golang function closure in testing Apr 24, 2024 am 08:54 AM

Go language function closures play a vital role in unit testing: Capturing values: Closures can access variables in the outer scope, allowing test parameters to be captured and reused in nested functions. Simplify test code: By capturing values, closures simplify test code by eliminating the need to repeatedly set parameters for each loop. Improve readability: Use closures to organize test logic, making test code clearer and easier to read.

Summary of the advantages and disadvantages of golang anonymous functions and closures Summary of the advantages and disadvantages of golang anonymous functions and closures May 05, 2024 am 09:54 AM

Anonymous functions are concise and anonymous, but have poor readability and are difficult to debug; closures can encapsulate data and manage state, but may cause memory consumption and circular references. Practical case: Anonymous functions can be used for simple numerical processing, and closures can implement state management.

See all articles