this

Undong·2023년 4월 6일
post-thumbnail

this

대부분의 경우 this의 값은 함수를 호출한 방법에 의해 결정됩니다. 실행중에는 할당으로 설정할 수 없고 함수를 호출할 때 마다 다를 수 있습니다. ES5는 함수를 어떻게 호출했는지 상관하지 않고 this 값을 설정할 수 있는 bind 메서드를 도입했고, ES2015는 스스로의 this 바인딩을 제공하지 않는 화살표 함수를 추가했습니다(이는 렉시컬 컨텍스트안의 this값을 유지합니다).

상황에 따른 this

1. 단독호출

function f1() {
  return this;
}

// 브라우저
f1() === window; // true

// Node.js
f1() === global; // true

엄격 모드에서는 기본 바인딩 대상에서 전역 객체는 제외된다.

'use strict'
window.a = 20;

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

foo(); // TypeError: Cannot read property 'a' of undefined

2. 함수안에서 this

function myFunction() {
  return this;
}
console.log(myFunction()); //Window

3. 메서드 안에서 쓴 this

var person = {
  firstName: 'John',
  lastName: 'Doe',
  fullName: function () {
    return this.firstName + ' ' + this.lastName;
  },
};
 
person.fullName(); //"John Doe"

4. 이벤트 핸들러 안에서 쓴 this

var btn = document.querySelector('#btn')
btn.addEventListener('click', function () {
  console.log(this); //#btn
});

5. 생성자 함수 안에서 쓴 this

생성자 함수는 객체를 만들 때 사용되며, this 키워드는 현재 생성되는 객체를 가리킵니다. 즉, 생성자 함수 안에서 this는 생성되는 객체를 참조하는데 사용됩니다.
여기서 this는 새로운 Person 객체를 가리키며, name은 이 객체의 프로퍼티로 설정됩니다. 새로운 객체를 만들기 위해서는 다음과 같이 new 키워드를 사용하여 생성자 함수를 호출합니다.

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

var kim = new Person('kim');
var lee = new Person('lee');

console.log(kim.name); //kim
console.log(lee.name); //lee

new를 빼는 순간 일반 함수 호출과 같아져서 this가 window에 바인딩된다. 

## **6. 명시적 바인딩을 한 this (call, apply, bind 메서드 사용)**

### **call **
>메서드의 호출 주체인 함수를 즉시 실행하도록 하는 명령이다. 이때 call은 첫 번째 this로 바인딩하고, 이후의 인자들을 호출할 함수의 매개변수로 하는 것이다. 함수를 그냥 실행하면 this는 전역객체를 참조하지만, call을 이용하면 임의의 객체를 this로 지정할 수 있다. 

```js 
var func = function (a, b, c) {
  console.log(this, a, b, c);
};

func(1, 2, 3);
func.call({ x: 1 }, 1, 2, 3);

apply

apply 메서드는 call 메서드와 기능적으로 완전히 동일하다.
call 메서드는 첫 번째 인자를 제외한 나머지 모든 인자들을 호출할 함수의 매개변수르 지정하는 반면, apply 메서드는 두 번째 인자를 배열로 받아 그 배열의 요소들을 매개변수로 지정한다

var func = function (a, b, c) {
  console.log(this, a, b, c);
};

func.apply({ x: 1 }, [4, 5, 6]);

var obj = {
  a: 1,
  method: function (x, y) {
    console.log(this.a, x, y);
  },
};

obj.method.apply({ a: 4 }, [5, 6]);

bind

bind 메서드는 ES5에서 추가된 기능으로, call과 비슷하지만 즉시 호출하지는 않고 넘겨 받은 this 및 인수들을 바탕으로 새로운 함수를 반환하기만 하는 메서드다.
bind 메서드는 함수에 this를 미리 적용하는 것과 부분 적용 함수를 구현하는 두 가지 목적을 모두 지닌다.

var func = function (a, b, c, d) {
  console.log(this, a, b, c, d);
};

func(1, 2, 3, 4); // Window{...} 1 2 3 4

var bindFunc1 = func.bind({ x: 1 });
bindFunc1(5, 6, 7, 8); // { x: 1 } 5 6 7 8

var bindFunc2 = func.bind({ x: 1 }, 4, 5);

bindFunc2(6, 7); // { x: 1 } 4 5 6 7
bindFunc2(8, 9); // { x: 1 } 4 5 8 9

7. 화살표 함수

화살표 함수는 실행 컨텍스트 생성 시 this를 바인딩하는 과정이 제외됐다.
즉 이 함수에는 this가 아예 없으며, 접근하고자 하면 스코프체인상 가장 가까운 this에 접근하게 된다.

var obj = {
  outer: function () {
    console.log(this); // { outer: [Function: outer] }
    var innerFunc = () => {
      console.log(this); // { outer: [Function: outer] }
    };
    innerFunc();
  },
};
obj.outer();
profile
console.log("Hello")

0개의 댓글