[TIL]201128

슬지로운 개발생활·2020년 11월 28일
0

TIL

목록 보기
43/73
post-thumbnail

1. STUDY

This

  • this는 기본적으로 Window의 객체를 말한다.
    (this라는건 하나의 스코프내에서 객체를 가르키는 값)
  • this는 콜스택에 올라가 있는 동안에만 접근이 가능하다고 해서 this랑 실행컨텍스트를 동일 선상이 두고 본다.

단순 호출

function f1() {
  return this;
}

// 브라우저
f1(); // window객체: f1() === window;
function f2(){
  "use strict"; // 엄격 모드 참고
  return this;
}

f2(); // undefined
// 엄격모드가 function f2 밖에 위치해도 똑같이 undefined

this의 값이 바뀌는 경우

객체의 메소드를 호출하는 경우

var prop = 25;
var o = {
  prop: 37,
  func: function() {
    return this.prop;
  },
  arrow: () => {
    console.log(this.prop);
  },
};

console.log(o.func()); // 37
console.log(o.arrow()); // 25
// arrow의 this는 window객체를 가르키고 있다.
// 전역스코프에 let / const로 선언하면 o.arrow()값은 undefined가 된다.
};
  • function 키워드는 해당객체를 바인딩하여 this의 값 변경
  • () => {}은 상위 객체의 this를 받는다.
    - 자신을 감싼 정적 범위(lexical context)이다. 전역 코드에서는 전역 객체를 가리킨다.

생성자를 통해 객체를 생성하는 경우

function person(name, age, job) {
  this.name = name;
  this.age = age;
  this.job = job;
}
// 생성자를 사용하지 않는 경우 : 단순 호출
let John = person('John', 20, student);
console.log(John); // undefined

// 생성자를 통한 객체 생성
let Vicky = person('Vicky', 32, Artist);
console.log(Vicky); // person {name: "Vicky", age: 32, job: Artist}

this가 해당 객체에 바인딩 되어 해당 값을 읽는다.

예외적인 경우

일부 라이브러리에서 엘리먼트에 이벤트를 추가할 때, 콜백함수에서 this를 사용하면 값이 바뀌는 경우가 있다.

apply(), call(), bind()

this는 이 3개를 이해하기 위한 발판이다.
this를 자유자제로 바꿀 수 있는 메소드 :

  • apply() : call 함수와 유사하지만, 매개변수는 배열로 받는것에 있어 차이가 있다.
  • call() : 객채를 바인딩 함과 동시에 호출을 한다.
  • bind() : 바인딩이된 함수를 반환하며, 한번더 호출시 함수를 실행한다.
const Jannie = {
  name: 'Jannie',
  age: 25,
  gender: 'female',
};

function printProfile() {
  console.log(this.name, this.age, this.gender);
}

let applying = printProfile.apply(Jannie);
// applying 값이 할당되지 않고 바로 출력된다 : applying === undefined
// Jannie 25 female
let calling = printProfile.call(Jannie); 
// calling 값이 할당되지 않고 바로 출력된다. : calling === undefined
// Jannie 25 female
let binding = printProfile.bind(Jannie); 
console.log(binding) 
// ƒ printProfile() {
//   console.log(this.name, this.age, this.gender);
// }
console.log(binding()) // Jannie 25 female

참조:

0개의 댓글