P4Ch4.함수- this

this

this는 일반 함수와 화살표 함수에서 다르게 정의된다.

  • 일반함수: 호출 위치에서 정의
  • 화살표 함수: 자신이 선언된 함수의 상위 스코프의 this를 상속받는다.
1
2
3
4
5
6
7
8
9
10
11
12
13
const user = {
	firstName: 'Heropy'
	lastNAme: 'Parl',
	regularFunction: function() {
		return `${this.firstName} ${this.lastName}`
	}
	arrowFunction: () => {
		return `${this.firstName} ${this.lastName}`
	}
}

console.log(user.regularFunction()) //Heropy Parl
console.log(user.arrowFunction()) //undefined

regularFuntion에서의 this는 일반 함수로부터 정의되었기 때문에 user객체 데이터를 나타내고 있다.

반면 arrowFunction에서의 this는 화살표 함수로부터 정의되었다. 따라서 함수가 정의된 위치에서의 상위 스코프에서의 this를 참조한다.

→ 이때 상위 스코프는 전역 스코프가 되며, 전역 스코프에서 name은 정의되지 않았기 때문에 undefined가 출력된다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
function user() {
	this.firstName = 'Neo'
	this.lastNAme = 'Anderson'
	return {
		firstName: 'Heropy'
		lastNAme: 'Parl',
		arrowFunction: () => {
			return `${this.firstName} ${this.lastName}`
		}
	}
}

const u = user()
console.log(u.arrowFunction()) //Neo Anderson

위의 예시와 같이 함수 내부에서 화살표 함수를 통해 this를 사용한 경우 화살표 함수의 this는 화살표 함수의 상위 스코프, 즉 함수 user에서의 this를 상속받는다. 따라서 화살표 함수 내의 this는 user 함수 데이터를 나타낸다.

어떤 객체 데이터의 메소드를 다른 객체 데이터가 빌려 쓸 수 있다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
const user = {
	firstName: 'Heropy'
	lastNAme: 'Parl',
	regularFunction: function() {
		return `${this.firstName} ${this.lastName}`
	}
}

const lewis = {
	firstName: 'Lewis'
	lastNAme: 'Yang',
}

console.log(user.regularFunction.call(lewis)) //Lewis Yang

일반 함수의 this는 호출 위치에서 정의된다.

따라서 lewis 객체 데이터가 user 객체 데이터가 지닌 regularFunction을 call했을 때 정의된 this는 lewis객체 데이터가 된다.