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

What's the difference between .call and .apply ?

Câu trả lời

The primary difference between .call() and .apply() in JavaScript lies in how they handle arguments passed to the function they are invoking. Both methods are used to invoke a function with a specified this context, allowing you to control the execution context of the function.

.call() Method

The .call() method calls a function with a given this value and arguments provided individually. This method is particularly useful when you know the number of arguments to pass to the function. The syntax for .call() is as follows:

javascript Copy
function.call(thisArg, arg1, arg2, ...);

Here, thisArg is the value to use as this for the function call, and arg1, arg2, ... are the arguments to pass to the function. Each argument is passed separately.

.apply() Method

The .apply() method, on the other hand, calls a function with a given this value and arguments provided as an array (or an array-like object). This method is useful when the number of arguments is not known until runtime or when the arguments are already in an array or array-like format. The syntax for .apply() is:

javascript Copy
function.apply(thisArg, [argsArray]);

In this syntax, thisArg is the value to use as this, and argsArray is an array or array-like object containing the arguments to pass to the function.

Practical Example

Consider a scenario where you have a function that adds two numbers, and you have these numbe...

middle

middle

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

senior

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

middle

Why is extending built-in JavaScript objects not a good idea?

middle

What advantages are using arrow functions?

Bình luận

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

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