[Javascript] this

SungWoo·2024년 10월 24일

자바스크립트 공부

목록 보기
12/42
post-thumbnail

this

this는 자신이 속한 객체 또는 자신이 생성할 인스턴스를 가리키는 자기 참조 변수다.

  • this를 통해 자신이 속한 객체 또는 자신이 생성할 인스턴스의 프로퍼티나 메서드를 참조할 수 있다.
  • this는 자바스크립트 엔진에 의해 암묵적으로 생성되며, 코드 어디서든 참조할 수 있다.
  • 함수를 호출하면 arguments 객체와 this가 암묵적으로 함수 내부에 전달된다.
  • 함수 내부에서 arguments 객체를 지역 변수처럼 사용할 수 있는 것처럼 this도 지역 변수처럼 사용할 수 있다.
  • 단, this가 가리키는 값, 즉 this바인딩은 함수 호출 방식에 의해 동적으로 결정된다.

함수 호출 방식과 this 바인딩

this 바인딩은 함수 호출 방식, 즉 함수가 어떻게 호출되었는지에 따라 동적으로 결정된다.
함수를 호출하는 방식은 다음과 같이 다양하다.

  1. 일반 함수 호출
  2. 메서드 호출
  3. 생성자 함수 호출
  4. Function.prototype.apply/call/bind 메서드에 의한 간접 호출

1. 일반 함수 호출

기본적으로 this에는 전역 객체가 바인딩된다.

  • 하지만 객체를 생성하지 않는 일반 함수에서 this는 의미가 없다.
  • strict mode가 적용된 일반 함수 내부의 this에는 undefined가 바인딩된다.
  • 일반 함수로 호출된 모든 함수(중첩 함수, 콜백 함수 포함) 내부의 this에는 전역 객체가 바인딩된다.
function foo() {
	console.log("foo's this: ", this);  // window
    function bar() {
		console.log("bar's this: ", this);  // window
    }
}
function foo() {
	'use strict';

	console.log("foo's this: ", this);  // undefined
    function bar() {
		console.log("bar's this: ", this);  // undefined
    }
}

2. 메서드 호출

메서드 내부의 this는 메서드를 소유한 객체가 아닌 메서드를 호출한 객체에 바인딩된다.

const person = {
	name: 'Lee',
    getName() {
    	return this.name;
    }
}

console.log(person.getName());  // Lee

  • 메서드는 프로퍼티에 바인딩된 함수다.
  • 즉, person 객체의 getName 프로퍼티가 가리키는 함수 객체는 person 객체에 포함된 것이 아니라 독립적으로 존재하는 별도의 객체이고, getName 프로퍼티가 함수 객체를 가리키고 있을 뿐이다.

3. 생성자 함수 호출

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

function Circle(radius) {
	this.radius = radius;
    this.getDiameter = function() {
    	return 2 * this.radius;
    }
}

const circle1 = new Circle(5);
const circle2 = new Circle(10);

console.log(circle1.getDiamter());  // 10
console.log(circle2.getDiamter());  // 20

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

  • apply, call, bind 메서드는 Function.prototype의 메서드이므로 모든 함수가 상속받아 사용할 수 있다.
  • apply, call 메서드는 this로 사용할 객체와 인수 리스트를 인수로 전달받아 함수를 호출한다.
  • bind 메서드는 첫 번째 인수로 전달한 값으로 this 바인딩이 교체된 새로운 함수를 반환한다.
function getThisBinding() {
	console.log(arguments);
    return this;
}

const thisArg = { a: 1 };

console.log(getThisBinding.apply(thisArg, [1, 2, 3]));
// Arguments(3) [1, 2, 3, callee: ƒ, Symbol(Symbol.iterator): ƒ]
// { a: 1 } 
console.log(getThisBinding.call(thisArg, 1, 2, 3));
// Arguments(3) [1, 2, 3, callee: ƒ, Symbol(Symbol.iterator): ƒ]
// { a: 1 } 
function getThisBinding() {
    return this;
}

const thisArg = { a: 1 };

console.log(getThisBinding.bind(thisArg));  // getThisBinding
console.log(getThisBinding.bind(thisArg)());  // { a: 1 } 
  • bind 메서드는 메서드의 this와 메서드 내부의 중첩 함수 또는 콜백 함수의 this가 불일치하는 문제를 해결하기 위해 유용하게 사용된다.
const person = {
	name: 'Lee',
    foo(callback) {
    	setTimeout(callback.bind(this), 100);
    }
}

person.foo(function() {
	console.log(`Hi! my name is ${this.name}.`);  // Hi! my name is Lee
}

profile
어제보다 더 나은

0개의 댓글