본문 바로가기

프론트엔드 개발을 위한 자바스크립트_프로그래머스 스쿨

자바스크립트 this란?

this 키워드는 함수나 메소드가 호출될 때 어떤 Object에 초점을 맞출 것인지 결정할 수 있습니다.

아래와 같은 규칙으로 this 키워드가 무엇을 참조하는지 즉, 이 함수가 어디에서 호출되는지 확인해 볼 수 있습니다.

  1. Implicit Binding
  2. Explicit Binding
  3. new Binding

1.Implicit Binding

일반적인 규칙이다. 

.의 왼쪽에 있는 object를 찾으면 그게 this가 참조하고 있는 것이다.

const user = { 
  name: "Tyler",
  age: 27,
  greet() {
    alert(`Hello, my name is ${this.name}`)
  }
}

user.greet() // Hello, my name is Tyler

 

2.Explicit Binding

아래와 같이 greet 함수가 user object에 속한 메서드가 아니라 단독함수라면

function greet() {
  alert(`Hello, my name is ${this.name}`)
}

const user = {
  name: "Tyler",
  age: 27
}

call 함수를 통해서 greet 함수를 호출할 수 있다. this 키워드가 무엇을 참조할 지 명시적으로 알려주는 방법이다.

greet.call(user)

만약 파라미터가 필요한 함수라면

function greet(l1, l2, l3) {
  alert(`Hello, my name is ${this.name} and I know ${l1}, ${l2}, and ${l3}`)
}
const languages = ["JavaScript", "Ruby", "Python"]
greet.call(user, languages[0], languages[1], languages[2])

call 함수의 첫번째 인자로 컨텍스트를 넣은 다음, 차례대로 인자를 넣어주면 된다.

 

apply 함수를 통해서 한번에 배열로 넣어 줄 수 있다.

greet.apply(user, languages)

 

3.new Binding

new 키워드로 함수를 호출하면 자바스크립트 인터프리터는 새로운 Object를 리턴하는데 

this는 그 새로운 Object를 참조한다.

function Band(name) {
    // 파라메터로 받은 name을 this.name으로 할당
    this.name = name;
    // Band 함수에 perform 함수를 만들고 그것을 this.perform 에 할당
    this.perform = function(){
      console.log(`${this.name} 밴드가 공연을 합니다!`);
    }
}
  // new 키워드를 이용해 Band 여러개를 만들기
  // new를 붙이고 함수가 실행될 때마다, 함수 내 this는 새 함수 인스턴스를 가리킵니다.
  var band1 = new Band('Cold Play')
  var band2 = new Band('Maroon5')

  band1.perform()
  band2.perform()

 

참고:

programmers.co.kr/learn/courses/11185

 

[스터디/10기] 프론트엔드 개발을 위한 자바스크립트(feat. VanillaJS)

× [본 과정은 마감되었습니다] 여기를 눌러 미리 대기자 신청 을 해주시면 할인 쿠폰과 함께 가장 먼저 연락드릴게요! 프론트엔드 개발을 위한 자바스크립트 온라인 스터디 시니어 프론트엔드

programmers.co.kr

mingcoder.me/2020/02/27/Programming/JavaScript/this/#new-Binding

 

자바스크립트 this란 대체 무엇인가?

자바스크립트에서 가장 오해하기 쉬운 개념 중 하나가 this 키워드다. 이 글에서 this 키워드가 무엇을 참조하는지 알아낼 수 있는 5가지 법칙을 배울거다. 암묵적 바인딩, 명시적 바인딩, new 바인

mingcoder.me