this란

2019-01-17

this란 무엇인가?
자바스크립트 개발자로 어느덧 2년차가 되어가지만 this가 뭐냐고 물으면 답을 못할 것 같다.
그러므로 this에 대해 정리해보자.

###1. 실행문맥
this란 실행문맥 즉, 호출자가 누구인지를 의미한다.

1
2
3
4
5
6
const caller = {
f: function() {
alert(this === window)
},
}
caller.f() // false, 호출자는 caller 객체

###2. 생성자 함수내의 this는 new를 통해 만들어진 새로운 변수

1
2
3
4
5
6
7
8
9
10
11
function NewObject(name, color) {
this.name = name
this.color = color
this.isWindow = function() {
return this === window
}
}

const newObj = new NewObject('nana', 'yellow')
console.log(newObj.name) // nana
console.log(newObj.color) // yellow

###3. bind, arrow function

1
2
3
4
5
6
7
8
9
function Family(firstName) {
this.firstName = firstName
const names = ['bill', 'mark', 'steve']

names.map((value, index) => {
console.log(value + ' ' + this.firstName)
})
}
const kims = new Family('kim')

실행하면 콘솔에 this.firstName값이 undefined로 찍히게 된다.
이는 map의 context(this)로 바인딩 되지 않기 때문이다. 그래서 bind.this(this)를 붙이거나
ES6부터는 arrow function(=>)을 사용하면 된다.

1
2
3
4
5
6
7
8
9
function Family(firstName) {
this.firstName = firstName
const names = ['bill', 'mark', 'steve']

names.map((value, index) => {
console.log(value + ' ' + this.firstName)
})
}
const kims = new Family('kim')