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

In JavaScript, why is the ...

Câu trả lời

In JavaScript, the this keyword is often considered inconsistent because its value can change depending on the context in which a function is called, rather than where it is defined. The rules governing the value of this can be subtle and varied, leading to confusion among developers, especially those coming from languages with different rules for this or self.

Here are the main reasons for the perceived inconsistency of this in JavaScript:

  1. Global Context: When a function is called in the global context, without being attached to any object, this refers to the global object. In a browser, this is typically the window object, and in Node.js, it is the global object[6][8].

  2. Function Context: When a function is called as a method of an object, this refers to the object the method is called on. This is the case even if the function is defined elsewhere and later attached to the object[4][6].

  3. Constructor Context: When a function is used as a constructor with the new keyword, this refers to the newly created instance that the constructor function returns[4][10].

  4. Strict Mode: In strict mode, the value of this remains undefined in functions that are called in the global context, which is a change from the default behavior where this refers to the global object[3][4].

  5. Indirect Invocation: When using call, apply, or bind methods, this can be explicitly set to any object, regardless of the initial context of the function[3][4].

  6. Arrow Functions: Arrow functions do not have their own this binding. Instead, they capture the this value of the enclosing execution context at the time they are created. This means that inside an arrow function, this is the same as it was outside the function[1][2][5].

  7. Event Handlers: In the context of DOM event handlers, this refers to the element that received the event, which can be different from the context in which the handler function was defined[6].

The combination of these different rules can make the behavior of this seem inconsistent, particularly when functions are passed around as arguments to other functions or used in callbacks, where the context of the funct...

expert

expert

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

senior

What's the difference between a variable that is: null , undefined or undeclared? How would you go about checking for any of these states?

middle

What are the differences between ES6 class and ES5 function constructors?

expert

Can you give an example of a curry function and why this syntax offers an advantage?

Bình luận

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

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