22장 this

박찬미·2024년 1월 27일
0

22.1 this 키워드

동작을 나타내는 메서드는 자신이 속한 객체의 상태인 프로퍼티를 참조하고 변경할 수 있어야 한다.
-> 이 때 메서드가 자신이 속한 객체의 프로퍼티를 참조하려면 먼저 자신이 속한 객체를 가리키는 식별자를 참조할 수 있어야 한다.

// 객체 리터럴
const circle = {
  radius: 5,
  getDiameter() {
    // this는 메서드를 호출한 객체를 가리킨다.
    return 2 * this.radius;
  }
};

console.log(circle.getDiameter()); // 10
// 생성자 함수생성
function Circle(radius) {
  // this는 생성자 함수가 생성할 인스턴스를 가리킨다.
  this.radius = radius;
}

//프로토타입 메서드  
Circle.prototype.getDiameter = function () {
  // this는 생성자 함수가 생성할 인스턴스를 가리킨다.
  return 2 * this.radius;
};

// 인스턴스 생성
const circle = new Circle(5);
console.log(circle.getDiameter()); // 10

22.2 함수 호출 방식과 this 바인딩

22.2.1 일반 함수 호출

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

function foo() {
  console.log("foo's this: ", this);  // window
  function bar() {
    console.log("bar's this: ", this); // window
  }
  bar();
}
foo();

위의 예제처럼 일반 함수로 호출하면 함수 내부의 this에는 전역 객체가 바인딩 된다.
엄격 모드일 경우는 undefined가 바인딩된다.

22.2.2 메서드 호출

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

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

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

person 의 객체에는 name 속성과 getName 메서드를 가지고 있다.
getName 메서드 내에서 this는 메서드가 호출된 객체를 가리킴....
이 경우 person.getName()을 호출할 때 this는 person 객체를 가리킴..

22.2.3 생성자 함수 호출

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

// Circle 생성자 정의
function Circle(radius) {
// 원 객체에 반지름 속성 
  this.radius = radius;
  // 원 객체에 getDiameter메서드 정의
  this.getDiameter = function () {
    return 2 * this.radius;
  };
}

// 반지름 5 객체 생성
const circle1 = new Circle(5);
// 반지름 10 객체 생성
const circle2 = new Circle(10);

console.log(circle1.getDiameter()); // 10
console.log(circle2.getDiameter()); // 20

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

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

apply,call,bind 메서드는 Funtion.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 }

profile
우당탕탕

0개의 댓글