관리 메뉴

Jerry

[JS]this에 대해 알아보기 본문

Front/JavaScript

[JS]this에 대해 알아보기

juicyjerry 2023. 3. 3. 15:55
반응형

자바스크립트에서 함수 호출 방식에 따라(어떻게 호출되었는지에 따라) this에 바인딩되는 객체가 동적으로 달라진다.

 

수의 상위 스코프를 결정하는 방식인 렉시컬 스코프(Lexical scope)는 함수를 선언할 때 결정된다.
this 바인딩과 혼동하지 않도록 주의하기 바란다.

 

 

 

함수의 호출하는 방식

1. 함수 호출
2. 메소드 호출
3. 생성자 함수 호출
4. apply/call/bind 호출

 

 

var foo = function () {
  console.dir(this);
};

// 1. 함수 호출
foo(); // window
// window.foo();

// 2. 메소드 호출
var obj = { foo: foo };
obj.foo(); // obj

// 3. 생성자 함수 호출
var instance = new foo(); // instance

// 4. apply/call/bind 호출
var bar = { name: 'bar' };
foo.call(bar);   // bar
foo.apply(bar);  // bar
foo.bind(bar)(); // bar

 

 

 

 

 

 

 

 

 

 

 

 

 

 


 

 

 

 

 

 

 

0. 단독 호출

단독 호출 시 global object를 가리킴

 

 

 

 

 

 

 

 

 

 

 

1. 함수 호출

[엄격모드X] this의 값이 호출에 의해 설정되지 않으므로, 기본값으로 브라우저에서는 window 전역 객체를 참조 (node.js는 global 전역 객체를 참조)

 

function foo() {
    return this;
}

foo() === window; // true

 

[엄격모드O] this의 값은 실행 컨텍스트에 진입하며 설정되는 값을 유지하므로, this는 undefined로 남아있다.

function foo() {
    "use strict";
    return this;
}
foo() === window; // false

 

 

 

 

 

 

 

 

 

 

2. 메소드 호출

함수를 어떤 객체의 메서드로 호출하면 this의 값은 그 객체를 사용

이 행동이 함수가 정의된 방법이나 위치에 전혀 영향을 받지 않는 것에 유의해라.

 

var o = {
  prop: 37,
  f: function() {
    return this.prop;
  }
};

console.log(o.f()); // 37

 

 

 

 

 

 

 

 

 

3. 생성자 함수 호출

함수를 new 키워드와 함께 생성자로 사용하면 this는 새로 생긴 객체에 묶입니다.

생성자 함수가 생성하는 객체로 this가 바인딩 됩니다.

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

 

 

 

 

 

 

 

 

 

4. apply/call/bind 호출 (명시적 바인딩)

call()도 apply()와 거의 같습니다.

차이점이 있다면 call()은 인수 목록을 받고 apply()는 인수 배열을 받는다는 차이가 있어요.

function Character(name, level) {
  this.name = name;
  this.level = level;
}
 
function Player(name, level, job) {
  Character.apply(this, [name, level]);
  this.job = job;
}
 
var me = new Player('Nana', 10, 'Magician');
 

 

 

 

 

 

 

5. 화살표 함수

화살표 함수에서 this는 자신을 감싼 정적 범위입니다. 전역 코드에서는 전역 객체를 가리킵니다.

var globalObject = this;
var foo = (() => this);
console.log(foo() === globalObject); // true

 

 

 

 

 

 

Source

https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Operators/this#%EC%A0%84%EC%97%AD_%EB%AC%B8%EB%A7%A5
https://nykim.work/71
https://poiemaweb.com/js-this

 

반응형