[JS] this

Fleuve·2020년 10월 4일
0
post-thumbnail

모든 함수 scope내에서 자동으로 설정되는 특수한 식별자를 this라고 한다.
excution context의 구성요소 중 하나로, 함수가 실행되는 동안 사용할 수 있다.

  • this의 5가지 패턴

1. Global: window

2. Function 호출: window

//Global
let name = 'Global varidable';
console.log(this.name)// 'Global varidable'

//Function 호출
function foo() {
  console.log(this.name);
}
foo();// 'Global variable';

3. Method 호출: 부모 Object

let counter = {
  val: 0,
  increment: function() {
    this.val += 1;
  }
}
counter.increment();
console.log(counter.val);// 1

Method를 호출하게 되면 this는 부모 Object를 가리키게 된다.
위 예제에서의 increment의 this는 counter객체를 가리킨다.

4. Construction mode(new 연산자로 생성된 function영역의 this): 새로 생성된 객체

function F(v){
  this.val = v;
}
let f = new F('WooHoo');
console.log(f.val)// 'WooHoo'
console.log(val)// ReferenceError

5. call or apply 호출: call, apply의 첫 번째 인자로 명시된 객체

function identify() {
  return this.name.toUpperCase();
}
function speak() {
  let greeting = `Hello, I'm ${identify.call(this)}`// 여기서 this는 {name:'kyle'}
  console.log(greeting);
}
let me = {name:'kyle'};
identify.call(me)// 'KYLE'
speak.call(me)// 'Hello, I'm KYLE'

0개의 댓글