Javascript에서 this는 어떻게 동작할까?

NSH·2022년 5월 16일
0

this 란?

자바스크립트의 함수는 호출될 때 인자 값 이외에 arguments 객체와 this를 암묵적으로 전달받는다.

function sum(number) {
	console.log(this); // window or global
  	console.log(arguments);
  	
  	return number + number;
}

sum(2);

자바스크립트의 this는 함수 호출 방식에 따라 바인딩되는 객체가 달라진다.

함수 호출 방식과 this 바인딩

자바스크립트는 함수 호출 방식에 따라서 this에 바인딩할 객체가 동적으로 결정된다.

함수를 선언할 때 this에 바인딩할 객체가 결정되는 것이 아니고, 함수 호출 방식에 따라 this에 바인딩할 객체가 동적으로 결정된다.

함수 호출

기본적으로 this는 전역 객체에 바인딩된다. 전역 함수, 내부 함수의 경우도 this는 전역 객체(window or global)에 바인딩된다.

// browser-side
function funA() { // 전역 함수
	console.log('funA this : ', this); // window
  	
  	function funB() { // 내장 함수
    	console.log('funB this : ', this); // window
    }
}

funA();

또한 메소드(함수가 객체의 프로퍼티 값)의 내부 함수도 this는 전역 객체에 바인딩된다.

const value = 100;

const obj = {
	value: 1000,
  	funA: function() { // 메소드
    	console.log('funA this : ', this); // obj
      	console.log('funA this.value', this.value); // 1000
    	
     	function funB() { // 내부 함수
          console.log('funA this : ', this); // window
          console.log('funA this.value', this.value); // 100
    	}
      
      	funB();
    },
}

obj.funA();

메소드 호출

함수가 객체의 프로퍼티 값이면 메소드로서 호출된다. 메소드의 this는 메소드를 호출할 객체에 바인딩된다.

// 1. 객체 메소드
const obj1 = {
	name: 'sangho',
    sayName: function() {
    	console.log(this.name);
    }
}

const obj2 = {
	name: 'hosang';
}

obj2.sayName = obj1.sayName;

obj1.sayName(); // sangho
obj2.sayName(); // hosang

// 2. 프로토타입 객체 메소드
// 프로토타입 관련 내용은 아래 글에서 자세히 다룬다.
function Person(name) {
	this.name = name;
}

Person.prototype.getName = function() {
	return this.name;
}

const me = new Person('Nam');
console.log('Name : ', me.getName()); // Nam

Person.prototype.name = 'Man';
console.log(Person.prototype.getName()); // Man

생성자 함수 호출

생성자 함수는 객체를 생성하는 역할을 한다. 자바스크립트에서 기존 함수에 new 연산자를 붙여서 호출하면 생성자 함수로 작동한다.

반대로 생성자 함수가 아닌데 new 연산자를 붙여서 호출하면 문제가 발생할 수 있다. 생성자 함수는 함수명 첫 문자를 대문자로 기술하여 혼란을 방지한다.

function Person(name) {
	this.name = name;
}

const me = new Person('Nam');
console.log(me); // Person { name: 'Nam' }

const you = Person('Man');
console.log(you); // undefined
console.log(window.name); // Man

new 연산자와 함께 생성자 함수를 호출하면 this 바인딩이 함수와 메소드로 호출할 때와 다르게 동작한다.

생성자 함수 동작 방식

new 연산자와 함께 생성자 함수를 호출하면 다음과 같은 순서로 동작한다.

  1. 빈 객체 생성 및 this 바인딩
    • 빈 객체 생성(생성자 함수 코드 실행 전 새로운 객체 생성)
    • 생성자 함수 내에서 사용되는 this는 빈 객체를 가르킨다.
    • 빈 객체는 생성자 함수의 prototype 프로퍼티가 가르키는 개체를 자신의 프로토타입 객체로 설정한다.
  2. this를 통한 프로퍼티 생성
    • 빈 객체에 this를 사용하여 동적으로 프로퍼티 및 메소드 생성
    • this는 빈 객체를 가르키므로 프로퍼티 및 메소드는 빈 객체에 추가된다.
  3. 생성된 객체 반환
    • 반환문이 없는 경우, this에 바인딩된 새로 생성한 객체를 반환한다.
    • 반환문이 새로 생성한 객체를 반환하지 않고 다른 객체를 반환하는 경우 생성자 함수로서의 역할을 수행하지 못한다.
function Person(name) {
    // 코드 실행 전 ------------- 1
	this.name = name;// ------- 2 
  	return this; // ----------- 3 보통은 생략한다.
}

객체 리터럴과 생성자 함수 방식의 차이

객체 리터럴과 생성자 함수 방식 차이는 프로토타입 객체([[prototype]])에 있다.

  • 객체 리터럴 방식의 경우, 생성된 객체의 프로토타입 객체는 Object.prototype 이다.
  • 생성자 함수 방식의 경우, 생성된 객체의 프로토타입 객체는 Function.prototype 이다.
// 객체 리터럴 방식
const obj = {
	name: 'name',
   	gender: 'male'
}

console.dir(obj);

// 생성자 함수 방식
function Person(name, gender) {
	this.name = name;
  	this.gender = gender;
}

let me = new Person('name', 'male')
console.dir(me);

new 연산자 없이 생성자 함수 호출

생성자 함수를 new 연산자 없이 호출한 경우 Person의 this는 전역 객체를 가르킨다. 위험성을 피하기 위해서 사용되는 패턴(Scope-Safe Constructor)는 대부분의 라이브러리에서 많이 사용된다.

참고로 빌트인 생성자(Object, Array 등)은 new 연산자와 함께 호출되었는지를 확인한 후 적절한 값을 반환한다.

// Scope-Safe Constroctor Pattern
function A(arg) {
	// this가 호출된 함수의 인스턴스가 아니면, new 연산자를 사용하지 않은 것이므로
	// new 연산자와 함께 생성자 함수를 호출하여 인스턴스를 반환한다.
	if(!(this instanceof arguments.callee)) {
		return new arguments.callee(arg);
	}

	// 프로퍼티 생성 및 값 할당
	this.value = arg ? arg : 0;
}

let a = new A(100);
let b = A(10);

console.log(a.value); // 100
console.log(b.value); // 10

callee는 arguments 객체의 프로퍼티로 함수 바디 내에서 현재 실행 중인 함수를 참조할 때 사용한다. 다시 말해서 함수 바디 내에서 실행 중인 함수의 이름을 반환한다.

apply / call / bind

this에 바인딩될 객체는 함수 호출 패턴에 의해서 결정된다. 자바스크립트 엔진의 암묵적 this 바인딩 이외에 this를 특정 객체에 명식적으로 바인딩하는 방법을 제공한다.

이것을 가능하게 하는 것은 모든 함수 객체의 프로토타입 객체인 Function.prototype 객체의 Function.prototype.apply, Function.prototype.call 메소드이다.

apply 메소드를 호출하는 주체는 함수이며 apply 메소드는 this를 특정 객체에 바인딩할 뿐 본질적인 함수 호출 기능이다.

const Person = function(name) {
	this.name = name;
}

const foo = {};

Person.apply(foo, ['Nam']);
console.log(foo); // { name: 'Nam'}

apply 메소드의 대표적인 용도는 유사 배열 객체에 배열 메소드를 사용하는 경우이다.

// 유사 배열
const obj = {
	0: 'a',
  	1: 'b',
  	2: 'c',
  	length: 4,
}

// 유사 배열에서 배열의 메소드를 사용하는 방법
// 1. Array.from
const obj2 = Array.from(obj);
obj.slice(0, 2);

// 2. apply, call, bind(es5) 사용
Array.prototype.slice.apply(obj, [0, 2]); // apply
Array.prototype.slice.call(obj, 0, 2); // call
const obj3 = Array.prototype.slice.bind(obj); // bind
obj3();

call 메소드는 apply와 기능이 같지만 apply의 두 번째 인자에서 배열 형태로 넘긴 것을 각각 하나의 인자로 넘긴다.

Array.prototype.slice.apply(obj, [0, 2]);
Array.prototype.slice.call(obj, 0, 2);

apply, call 메소드는 콜백 함수의 this를 위해서 사용한다.

function Person(name) {
	this.name = name;
}

Person.prototype.doSomething = function(callback) {
	if(typeof callback === 'function') {
    	callback(); // --- 1
    }
}

function foo() {
	console.log(this.name); // --- 2
}

var me = new Person('Nam');
me.toSomething(foo);

위 예제 코드의 1번 시점에서는 this는 Person 객체이다. 2번 시점에서 this은 window 객체이다. 콜백 함수 foo 를 호출하는 외부 함수의 this와 내부 함수의 this는 다르기 때문에 문제가 발생한다.

따라서 외부 함수와 내부 함수의 this를 일치시켜 주어야 하는 번거로움이 발생한다.

function Person(name) {
	this.name = name;
}

Person.prototype.doSomething = function(callback) {
	if(typeof callback === 'function') {
		callback.apply(this); 
	}
}

function foo() {
	console.log(this.name);
}

var p = new Person('nam');
p.doSomething(foo);

apply 메소드를 사용해서 콜백 함수의 this를 외부 함수의 this와 일치시켜준다.

ES5의 Function.prototype.bind를 사용하는 방법도 가능하다. Function.prototype.bind는 함수에 인자로 전달한 this가 바인딩된 새로운 함수를 리턴한다.

function Person(name) {
	this.name = name;
}

Person.prototype.doSomething = function(callback) {
	if(typeof callback === 'function') {
		const bindFunc = callback.bind(this);
		bindFunc(); 
	}
}

function foo() {
	console.log(this.name);
}

var p = new Person('nam');
p.doSomething(foo);

참고👀
https://poiemaweb.com/js-this

profile
잘 하고 싶다.

0개의 댓글