[ 자바스크립트 ] This

김수연·2022년 9월 25일
0
post-thumbnail

javascript 에서의 this는 다른 언어와 다르게 동작한다.
this의 값은 함수를 호출한 방법에 의해 결정되기 때문에 this가 어디 묶여 있는지 파악하는 것이 가장 중요하다

📌 암시적 바인딩

chrome 브라우저에서 this는 window, this.alert('hi')가 잘 작동하고 있다.

node 환경에서 this는 존재하지만 this.alert()는 존재하지 않는다.

전역공간 이외에도 함수에서의 this와 메서드의 this는 또 다를 수 있다.
이처럼 예상하기 어려운 this를 좀 더 안전하게 사용하는 방법을 살펴보자

📌 명시적 바인딩

Function.prototype.apply( )
Function.prototype.bind( )
Function.prototype.call( )

# call

const me = {
	name: 'suyeon',
  	sayName: function(){
    	return this.name + ' 입니다.';
    }
}

const zero = {
	name: '베이스',
  	sayName: function(){
    	return this.name + ' 입니다.';
    }
}

function sayFullName(lastName){
	return lastName + this.sayName();
}

const result = sayFullName.call(me,'kim');
const result2 = sayFullName.call(zero, '제로');

console.log(result); // kimsuyeon 입니다.
console.log(result2); // 제로베이스 입니다.

# apply

const me = {
	name: 'suyeon',
  	sayName: function(){
    	return this.name + ' 입니다.';
    }
}

const zero = {
	name: '베이스',
  	sayName: function(){
    	return this.name + ' 입니다.';
    }
}

function sayFullName(lastName){
	return arguments[0] + this.sayName();
}

const result = sayFullName.apply(me,['kim','김']);
const result2 = sayFullName.apply(zero, ['zero', '제로']);

console.log(result); // kimsuyeon 입니다.
console.log(result2); // zero베이스 입니다.

call과 같지만 배열을 인자로 받은 후 arguments[index] 형식으로 요소를 선택할 수 있다

bind

const me = {
	name: 'suyeon',
  	sayName: function(){
    	return this.name + ' 입니다.';
    }
}

const zero = {
	name: '베이스',
  	sayName: function(){
    	return this.name + ' 입니다.';
    }
}

function sayFullName(lastName){
	return lastName + this.sayName();
}

const sayFullNameMe = sayFullName.bind(me);
const sayFullNameZero = sayFullName.bind(zero);

console.log(sayFullNameMe('kim')); // kimsuyeon 입니다.
console.log(sayFullNameZero('제로')); // 제로베이스 입니다.
profile
길을 찾고 싶은 코린이 of 코린이

0개의 댓글