모던자바스크립트 22장 this

연호·2022년 12월 29일
0

모던자바스크립트

목록 보기
17/28

this

  1. this는 자신이 속한 객체 또는 자신이 생성할 인스턴스를 가리키는 자기 참조 변수다. this를 통해 자신이 속한 객체 또한 자신이 생성할 인스턴스의 프로퍼티나 메서드를 참조할 수 있다.
    단, this가 가리키는 값, 즉 this 바인딩은 함수 호출 방식에 의해 동적으로 결정된다.
const circle = {
  radius : 5,
  getDiameter() {
    // this 메서드는 호출한 객체를 가리킨다.
    return 2 * this.radius;
  }
};

console.log(circle.getDiameter()); // 10
  1. 일반함수로 호출시, 함수 내부의 this에는 전역 객체가 바인딩된다. 또한 중첩 함수, 콜백 함수 등 모든 함수 내부의 this에도 전역 객체가 바인딩된다.
function foo() {
console.log("foo's this :",this); // window
  function bar(){
    console.log("bar's this :",this); // window
  }
  bar();
}
foo();
  1. 메서드 내부의 this에는 메서드를 호출한 객체가 바인딩 된다.
const person = {
  name : 'Lee',
  getName(){
    // 메서드 내부의 this는 메서드를 호출한 객체에 바인딩 된다.
    return this.name;
  }
};

// 메서드 getName을 호출한 객체는 person 이다.
console.log(person.getName()); // Lee
  1. 생성자 함수 내부의 this 에는 생성자 함수가 미래에 생성할 인스턴스가 바인딩 된다.
function Circle(radius){
  this.radius = radius;
  this.getDiameter = function () {
    return 2 * this.radius;
  };
}

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

console.log(circle1.getDiameter()); // 10
console.log(circle2.getDiameter()); // 20
  1. apply, call, bind 메서드는 Function.prototype의 메서드이다. apply와 call 메서드는 this로 사용할 객체와 인수 리스트를 인수로 전달받아 함수를 호출한다.
function getThisBinding(){
  return this;
}

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

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

// getThisBinding 함수를 호출하면서 인수로 전달한 객체를 getThisBinding 함수의 this에 바인딩한다.
console.log(getThisBinding.apply(thisArg)); // { a : 1 }
console.log(getThisBinding.call(thisArg)); // { a : 1 }

//applt 메서드는 인수를 배열로 묶어서 전달, call은 쉼표로 구분한 리스트 형식으로 전달한다. this로 사용할 객체를 전달하면서 함수를 호출하는 것은 동일하다.
  1. bind 메서드는 메서드의 this와 메서드 내부의 중첩 함수 또는 콜백 함수의 this가 불일치 하는 문제를 해결하기 위해 유용하게 사용된다.
const person = {
  name: "Lee",
  foo(callback){
    setTimeout(callback, 100);
  }
};

person.foo(function(){
  console.log(`Hi! my name is ${this.name}.`); // Hi! my name is .
  //일반 함수로 호출된 콜백 함수 내부의 this.name은 브라우저 환경에서 window.name과 같다.
});
const person = {
  name: "Lee",
  foo(callback){
    // bind 메서드로 callback 함수 내부의 this 바인딩을 전달
    setTimeout(callback.bind(this), 100);
  }
};

person.foo(function(){
  console.log(`Hi! my name is ${this.name}.`); // Hi! my name is Lee.
});
profile
뉴비

0개의 댓글