• Что бы вступить в ряды "Принятый кодер" Вам нужно:
    Написать 10 полезных сообщений или тем и Получить 10 симпатий.
    Для того кто не хочет терять время,может пожертвовать средства для поддержки сервеса, и вступить в ряды VIP на месяц, дополнительная информация в лс.

  • Пользаватели которые будут спамить, уходят в бан без предупреждения. Спам сообщения определяется администрацией и модератором.

  • Гость, Что бы Вы хотели увидеть на нашем Форуме? Изложить свои идеи и пожелания по улучшению форума Вы можете поделиться с нами здесь. ----> Перейдите сюда
  • Все пользователи не прошедшие проверку электронной почты будут заблокированы. Все вопросы с разблокировкой обращайтесь по адресу электронной почте : info@guardianelinks.com . Не пришло сообщение о проверке или о сбросе также сообщите нам.

Understanding `this` and Arrow Functions in JavaScript

Lomanu4 Оффлайн

Lomanu4

Команда форума
Администратор
Регистрация
1 Мар 2015
Сообщения
1,481
Баллы
155
In JavaScript, the this keyword is one of the most powerful yet often misunderstood concepts. Its behavior can vary depending on how a function is declared and invoked. This article explains how this works, how arrow functions affect it, and how to use both effectively in modern JavaScript.

The this Keyword in JavaScript


The value of this in JavaScript refers to the object that is executing the current function. It is determined by the context in which a function is called, not where it is defined.

Regular Function and this


In regular functions, the value of this depends on the call site (how the function is called).


function sayHello() {
console.log(this.name);
}

const person = {
name: 'Alice',
greet: sayHello
};

person.greet(); // Output: Alice

Here, the function sayHello is called as a method of the person object, so this refers to person.

However, if we call the function directly without an object context:


sayHello(); // Output: undefined (or window.name in non-strict mode)

In this case, this refers to the global object (window in browsers) or undefined in strict mode.

this Inside a Callback


One common pitfall with regular functions is the loss of context inside callbacks.


function Counter() {
this.count = 0;

setInterval(function () {
this.count++;
console.log(this.count);
}, 1000);
}

new Counter();

In this example, this inside setInterval does not refer to the instance of Counter, but to the global object. This results in NaN or an error because this.count is not defined.

Arrow Functions and this


Arrow functions behave differently. They do not have their own this. Instead, they inherit this from the enclosing lexical context at the time they are defined.


function Counter() {
this.count = 0;

setInterval(() => {
this.count++;
console.log(this.count);
}, 1000);
}

new Counter();

In this version, the arrow function captures this from the Counter function, so this.count refers to the correct object.

Arrow Functions in Object Methods


Arrow functions are not suitable as object methods if you rely on this referring to the object itself.


const person = {
name: 'Bob',
greet: () => {
console.log(this.name);
}
};

person.greet(); // Output: undefined

Here, this does not refer to person, but to the outer lexical scope, which might be the global object or undefined in strict mode.

Summary

  • Regular functions have dynamic this based on how they are called.
  • Arrow functions inherit this from the lexical scope in which they are defined.
  • Use arrow functions to retain context, especially for callbacks and closures.
  • Avoid using arrow functions as object methods when you need access to the object via this.

Understanding the nuances of this and how arrow functions change its behavior is essential for writing clean, predictable JavaScript code. By choosing the right function type for the job, you can avoid many common bugs and improve the readability of your code.


Пожалуйста Авторизируйтесь или Зарегистрируйтесь для просмотра скрытого текста.

 
Вверх Снизу