Câu hỏi phỏng vấn Javascript
Câu hỏi

What is a closure, and how/why would you use one?

Câu trả lời

A closure in computer programming is a concept where a function retains access to its lexical scope even when the function is executed outside that lexical scope. In simpler terms, a closure gives a function access to all the variables that were in scope at the time of the function's creation, regardless of the current scope. This is possible because the function 'remembers' the environment in which it was created.

Closures are commonly used for several reasons:

  1. Data Encapsulation and Privacy: Closures can be used to create private variables and methods. This is particularly useful in JavaScript because it does not provide native support for private members. By using closures, you can emulate private state.

  2. Maintaining State in Asynchronous Code: In JavaScript, closures are often used in callbacks for asynchronous functions to maintain state between the asynchronous calls.

  3. Currying: Closures allow for the partial application of functions, a technique known as currying. This is where a function with multiple parameters is broken down into a series of functions that each take a single argument.

  4. Module Pattern: Closures are at the heart of the module pattern in JavaScript, where a set of related methods and variables are encapsulated in a single object or module.

  5. Event Handlers: Closures are used in event handlers to ensure that the handler has access to variables that were in scope when the handler was bound to the event.

  6. Factory Functions: Closures can be used to create factory functions that can produce instances of objects with similar but isolated state.

  7. Memoization: Closures can be used to implement memoization, an optimization technique that caches the results of function calls for faster subsequent lookups.

Here is a simple example of a closure in JavaScript:

javascript Copy
function makeAdder(x) {
    return function(y) {
        return x + y;
    };
}

var add5 = makeAdder(5);
c...
middle

middle

Gợi ý câu hỏi phỏng vấn

junior

How to check if an object is an array or not? Provide some code

middle

Explain the differences on the usage of foo between function foo() {} and var
foo = function() {}

junior

What is a Polyfill?

Bình luận

Chưa có bình luận nào

Chưa có bình luận nào