모던자바스크립트 DeepDive : 22장 this

te-ing·2022년 4월 22일
0
post-thumbnail

this는 자신이 속한 객체 혹은 자신이 생성할 인스턴스를 가리키는 자기참조변수이다. this 바인딩은 함수 호출 방식에 의해 동적으로 결정되는데, 일반 함수호출, 메서드 호출, 생성자 함수 호출, 특정 메서드에 의한 간접호출로 나뉜다.

this는 자신이 속한 객체 또는 자신이 생성할 인스턴스를 가리키는 자기 참조 변수다. this를 통해 자신이 속한 객체 또는 자신이 생성할 인스턴스의 프로퍼티나 메서드를 참조할 수 있으며, this 바인딩은 함수 호출 방식에 의해 동적으로 결정된다.

함수 호출 방식과 this 바인딩

일반 함수 호출

var value = 1; // 전역객체
function foo() {
	console.log("foo's this: ", this); // window;
	function bar() {
		console.log("bar's this: ", this); // window
		console.log("bar's this: ", this.value); // 1
	}
	bar();
}
foo();

일반 함수로 호출된(중첩 함수, 콜백함수 포함)모든 함수 내부의 this에는 전역객체가 바인딩되며, strict mode에서는 undefined가 바인딩된다.


메서드 호출

const person = {
	name: 'Lee',
	getName() {
		return this.name; // 메서드를 호출한 객체에 바인딩
	}
};
console.log(person.getName()); // Lee

마침표 연산자 앞에 기술한 객체가 바인딩된다.


생성자 함수 호출

생성자 함수 내부의 this에는 생성자 함수가 생성할 인스턴스가 바인딩된다.


Function.prototype.apply/call/bind 메서드에 의한 간접 호출

function convertArgsToArray() {
	console.log(arguments);
	const arr = Array.prototype.slice.call(arguments);
	console.log(arr);
	return arr;
}
convertArgsToArray(1, 2, 3); // [1, 2, 3]
const person = {
	name: 'Lee'
	foo(callback) { 
		setTimeout(callback.bind(this), 100); // bind 메서드로 callback 함수 내부의 this 바인딩을 전달
	} // this가 전역객체 window가 아닌 함수 내부의 this를 바인딩하도록 만듦
};
person.foo(function () {
	console.log(`Hi! my name is ${this.name}.`}; // Hi! my name is Lee.
});

apply, call, bind 메서드는 Function.prototype의 메서드로, 모든 함수가 상속받아서 사용할 수 있다.
Function.prototype.apply / call / bind은 메서드에 첫번째 인수로 전달한 객체를 바인딩한다.

apply, call, bind 각각의 차이점

const Tom = {
  age: 25,
  gender: 'man',
};

function printProfile(name) {
  console.log(name, this.age, this.gender);
}

printProfile.apply(Tom, ['Tom']);// Tom 25 man
printProfile.call(Tom, 'Tom');// Tom 25 man
printProfile.bind(Tom, 'Tom').call();// Tom 25 man

apply : call 함수와 유사하지만, 매개변수는 배열로 받는 것에 있어 차이가 있다.

call : 객체를 바인딩 함과 동시에 호출을 한다.

bind : 바인딩이된 함수를 반환하며, 한번더 호출시 함수를 실행한다.

profile
병아리 프론트엔드 개발자🐣

0개의 댓글