Frontend Development: This

Peter Jeon·2023년 6월 27일
0

Frontend Development

목록 보기
30/80
post-custom-banner

JavaScript This Keyword

In JavaScript, the this keyword is a concept that often confuses new and even experienced developers. The this keyword refers to the object it belongs to. It has different values depending on where it is used. This blog post explores the use of this in JavaScript, offering an in-depth understanding of how it behaves within different contexts.

Global Context

Global Context

In a global execution context (outside of any function), this refers to the global object, whether in strict mode or not.

console.log(this); // Window {...} (browser environment)

Function Context

In a function context, the value of this depends on how the function is called.

  • In a simple function call (not a method or constructor), this will be the global object (window in a browser). But in strict mode, it will be undefined.
function simpleFunction() {
  console.log(this);
}

simpleFunction(); // Window {...} (browser environment)
  • When a function is called as an object method, this refers to the object.
const myObj = {
  method() {
    console.log(this);
  },
};

myObj.method(); // {method: ƒ}
  • When a function is called as a constructor (with the new keyword), this refers to the newly created instance.
function Car(make, model) {
  this.make = make;
  this.model = model;
}

const myCar = new Car('Toyota', 'Corolla');
console.log(myCar); // Car {make: 'Toyota', model: 'Corolla'}
  • When a function is invoked with call or apply, this refers to the object passed as the first argument.
function greet() {
  console.log(`Hello, ${this.name}`);
}

const user = { name: 'John' };

greet.call(user); // Hello, John

Arrow Functions

In arrow functions, this behaves differently. It takes the value of this from the enclosing lexical context. Here is an example:

const myObj = {
  name: 'John',
  regularFunction: function() {
    console.log(this.name); // John
  },
  arrowFunction: () => {
    console.log(this.name); // undefined
  },
};

myObj.regularFunction();
myObj.arrowFunction();

Conclusion

In JavaScript, the this keyword is a significant part of the language and understanding how it works in different contexts is crucial. It doesn't refer to the function itself or its lexical scope but is determined by how the function is called. Whether you're working with regular functions, object methods, constructors, or arrow functions, understanding this can help you write cleaner, more efficient code.

profile
As a growing developer, I am continually expanding my skillset and knowledge, embracing new challenges and technologies
post-custom-banner

0개의 댓글