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

Explain Function.prototype.bind .

Câu trả lời

Function.prototype.bind is a method in JavaScript that allows you to create a new function with a specific this context and optionally, initial arguments. When you bind a function, you are essentially creating a new function that, when called, has its this keyword set to the provided value, with a given sequence of arguments preceding any others that are provided when the new function is called.

Here's a breakdown of how Function.prototype.bind works:

  • Creating a Bound Function: When you call bind on a function, you are creating a new function that is permanently associated with the specified this value and initial arguments if provided. The syntax for bind is func.bind(thisArg[, arg1[, arg2[, ...]]]), where func is the function you want to bind, thisArg is the this value you want to use, and arg1, arg2, ... are the arguments you want to pass to the function when it is called[5].

  • Setting the this Context: The first argument to bind is the value that you want to be passed as the this context of the target function when the new function is called. If the value is null or undefined, the this value of the function will default to the global object (or undefined in strict mode)[4].

  • Partial Application: bind can also be used for partial application, where you create a new function by pre-filling some of the arguments to the original function. These arguments, if provided, follow the thisArg and are prepended to the arguments provided to the bound function when it is called[5].

  • Behavior with Object Methods: When binding an object method, bind ensures that the method retains the correct this context even when it is extracted from its object. For example, if you have an object method that you want to pass as a callback, using bind will ensure that the method stil...

middle

middle

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

senior

Can you give an example for destructuring an object or an array in ES6?

senior

How would you prevent Callback Hell without using promises, async or generators?

middle

What is the motivation for bringing Symbol to ES6?

Bình luận

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

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