sungyup's.

Web_Miscellaneous / 기초 개념 / 1.8 this의 용법

1.8this의 용법

this의 사용

1. 정의

현재 실행중인 함수를 참조하는 object이다. this의 값은 함수가 어떻게 호출되는지에 따라 결정된다.(어디서 정의되었는지가 아니라)

  • 함수를 호출할 때 함수가 어떻게 호출되었는지에 따라 this에 반인딩할 객체가 동적으로 결정

2. 세부

  1. Global Context

함수들 밖, 즉 글로벌 컨텍스트에서 쓰면 글로벌 컨텍스트 자체를 지칭

  • web browser에선 window
  • Node.js에선 global
  1. Function Context
  • strict mode에선 undefined, 아닐땐 window
javascript
'use strict'; function standaloneFunction() { console.log(this); } standaloneFunction(); // Logs undefined
  1. Method Context

함수가 object의 method로 불렸을때, this는 해당 Object를 지칭

javascript
const person = { name: 'Alice', greet: function () { console.log(this.name); }, }; person.greet(); // Logs "Alice"
  1. Constructor Context

new 키워드로 새로운 Object를 만드는 constructor function에서, this는 새로 만들어진 object instance를 지칭

javascript
function Person(name) { this.name = name; } const alice = new Person('Alice'); console.log(alice.name); // Logs "Alice"
  1. call, apply, bind
  • call 예시
javascript
function greet() { console.log(this.name); } const person = { name: 'Alice' }; greet.call(person); // Logs "Alice"
  • apply 예시
javascript
function greet(greeting) { console.log(greeting + ', ' + this.name); } const person = { name: 'Alice' }; greet.apply(person, ['Hello']); // Logs "Hello, Alice"
  • bind 예시
javascript
function greet() { console.log(this.name); } const person = { name: 'Alice' }; const boundGreet = greet.bind(person); boundGreet(); // Logs "Alice"
  1. 화살표 함수

화살표 함수는 자기 고유의 this 컨텍스트는 없으나, 자신을 감싸는 바깥 함수에서 상속

javascript
const person = { name: 'Alice', greet: function () { const innerFunction = () => { console.log(this.name); }; innerFunction(); }, }; person.greet(); // Logs "Alice"