모든 함수 scope내에서 자동으로 설정되는 특수한 식별자를 this라고 한다.
excution context의 구성요소 중 하나로, 함수가 실행되는 동안 사용할 수 있다.
//Global
let name = 'Global varidable';
console.log(this.name)// 'Global varidable'
//Function 호출
function foo() {
console.log(this.name);
}
foo();// 'Global variable';
let counter = {
val: 0,
increment: function() {
this.val += 1;
}
}
counter.increment();
console.log(counter.val);// 1
Method를 호출하게 되면 this는 부모 Object를 가리키게 된다.
위 예제에서의 increment의 this는 counter객체를 가리킨다.
function F(v){
this.val = v;
}
let f = new F('WooHoo');
console.log(f.val)// 'WooHoo'
console.log(val)// ReferenceError
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'