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

When should you NOT use arrow functi...

Câu trả lời

Arrow functions in ES6 are a concise and efficient way to write function expressions in JavaScript, but they are not suitable for all use cases due to their lexical scoping of this and other characteristics. Here are three or more cases when you should NOT use arrow functions:

  1. Object Methods: Arrow functions do not have their own this context; instead, they inherit this from the parent scope at the time they are defined. This can lead to unexpected behavior when using arrow functions as methods in an object literal, as this will not refer to the object itself but to the enclosing lexical context, which is often the global scope or the scope of the enclosing function[4][7][8][9].

  2. Function Constructors: Arrow functions cannot be used as constructors. They cannot be used with the new keyword because they do not have their own this context. Attempting to use an arrow function as a constructor will result in a TypeError because the arrow function does not have a prototype property[4][6].

  3. Event Handlers: When using arrow functions as event handlers, the this context will not be bound to the element that fired the event but will instead inherit this from the surrounding scope. This can lead to bugs and unexpected behavior if the handler relies on this to access the element or its properties[7][8].

  4. Prototype Methods: Since arrow functions do not have their own this context, they are not suitable for defining prototype methods where you expect this to refer to the instance of the object[2].

  5. Functions that use arguments Object: Arrow functions do not have their own arguments object. If you need to access the arguments object, which is an array-like object containing the arguments passed to a function, you should use a traditional function expression instead[5][6].

  6. Callback Functions with Dynamic Context: If you need the function to have a dynamic context, or if you are working with a func...

senior

senior

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

middle

What is Coercion in JavaScript?

senior

Explain how JSONP works (and how it's not really Ajax)

junior

What's the difference between throw Error('msg') vs throw new Error('msg') ?

Bình luận

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

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