티스토리 뷰

반응형

this

this는 자신이 속한 객체 또는 자신이 생성할 인스턴스를 가리키는 자기 참조 변수다. this를 통해 자신이 속한 객체 또는 자신이 생성할 인스턴스의 프로퍼티나 메서드를 참조할 수 있다.

 

this는 자바스크립트 엔진에 의해 암묵적으로 생성되며, 코드 어디서든 참조할 수 있다. 함수를 호출하면 arguments 객체와 this가 암묵적으로 함수 내부에 전달된다.


함수 호출 방식과 this 바인딩

this 바인딩은 함수 호출 방식, 즉 함수가 어떻게 호출되었는지에 따라 동적으로 결정된다.

 

🛑함수 호출 방식

  1. 일반 함수 호출
  2. 메서드 호출
  3. 생성자 함수 호출
  4. Function.prototype.apply/call/bind 메서드에 의한 간접 호출

 

1️⃣ 일반 함수 호출

기본적으로 this에는 전역 객체가 바인딩된다.

// 전역 함수
function foo() {
  console.log("foo's this: ", this); // window
  
  // 중첩 함수
  function bar() {
    console.log("bar's this: ", this); // window
  }
  
  bar();
}

foo();

일반 함수로 호출하면 함수 내부의 this에는 전역 객체가 바인딩된다.

 

🔻 strict mode

function foo() {
  // strict mode 적용
  'use strict'; 
  
  console.log("foo's this: ", this); // undefined
  
  function bar() {
    console.log("bar's this: ", this); // undefined
  }
  
  bar();
}

foo();

strict mode가 적용된 일반 함수 내부의 this에는 undefined가 바인딩된다.

 

 

2️⃣ 메서드 호출

메서드 내부의 this에는 메서드를 호출한 객체, 즉 메서드를 호출할 때 메서드 이름 앞의 마침표(.) 연산자 앞에 기술한 객체가 바인딩된다.

const person = {
  name: 'Lee',
  getName() {
    // 메서드 내부의 this는 메서드를 호출한 객체에 바인딩된다.
    return this.name;
  }
};

// 메서드 getName을 호출한 객체는 person이다.
console.log(person.getName()); // Lee

 

 

3️⃣ 생성자 함수 호출

생성자 함수 내부의 this에는 생성자 함수가 생성할 인스턴스가 바인딩된다.

function Circle(radius) {
  this.radius = radius;
  this.getDiameter = function () {
    return 2 * this.radius;
  };
}

// 반지름 5 객체 생성
const circle1 = new Circle(5);
console.log(circle1.getDiameter()); // 10

// 일반 함수로 호출
const circle2 = Circle(10);
console.log(circle2); // undefined

new 연산자로 생성하면 생성자 함수로, new 연산자로 생성 안 하면 일반 함수로 동작한다.

 

 

4️⃣ Function.prototype.apply/call/bind 메서드에 의한 간접 호출

apply와 call 메서드의 본질적인 기능은 함수를 호출하는 것이다.

function getThisBinding() {
  return this;
}

// this로 사용할 객체
const thisArg = { a: 1 };

console.log(getThisBinding()); // window

console.log(getThisBinding.apply(thisArg)); // { a: 1 }
console.log(getThisBinding.call(thisArg)); // { a: 1 }

 

 

 

bind 메서드는 함수를 호출하지 않고, this로 사용할 객체만 전달한다.

 

bind 메서드는 메서드의 this와 메서드 내부의 중첩 함수 또는 콜백 함수의 this가 불일치하는 문제를 해결하기 위해 유용하게 사용된다.

function getThisBinding() {
  return this;
}

// this로 사용할 객체
const thisArg = { a: 1 };

console.log(getThisBinding.bind(thisArg)); // getThisBinding

console.log(getThisBinding.bind(thisArg)()); // { a: 1 }

 

 

함수 호출 방식 this 바인딩
일반 함수 호출 전역 객체
메서드 호출 메서드를 호출한 객체
생성자 함수 호출 생성자 함수가 생성할 인스턴스
Function.prototype.apply/call/bind() 메서드에 의한
간접 호출
Function.prototype.apply/call/bind() 메서드에
첫 번째 인수로 전달한 객체

 

 

 

좋아요는 로그인하지 않아도 누를 수 있습니다!

728x90
반응형
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/04   »
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30
글 보관함