JavaScript&TypeScript

JavaScript의 this

hjkang

단독으로 쓰거나 함수 안에서의 this

  • Node.js에서는 global
  • 브라우저에서는 window
  • 엄격 모드에서는 undefined
function f1() {
  return this;
}

// 브라우저
console.log(f1()); // window
console.log(this); // window
f1() === window; // true

// Node.js
console.log(f1()); // global
console.log(this); // global
f1() === global; // true


function f2(){
  "use strict"; // 엄격 모드
  return this;
}

console.log(f2()); // undefined
f2() === undefined; // true
var num = 0;
function add() {
  this.num = 100;
  num++;
  
  console.log(num); // 101
  console.log(window.num); // 101
  console.log(num === window.num); // true
}
 
add();

 

 

메서드에서의 this

  • 메서드 내부 코드에서 사용된 this는 메서드를 호출한 객체로 바인딩
var person = {
  firstName: 'HJ',
  lastName: 'KANG',
  fullName: function () {
    return this.firstName + ' ' + this.lastName;
  },
};
 
person.fullName(); // "HJ KANG"


var num = 0;
 
function show() {
  console.log(this.num);
}
 
show(); // 0
 
var obj = {
  num: 100,
  func: show,
};
 
obj.func(); // 100

 

 

이벤트 핸들러 안에서의 this

  • 이벤트를 받는 HTML 요소
var btn = document.querySelector('#btn')
btn.addEventListener('click', function () {
  console.log(this); // #btn
});

 

 

생성자 안에서의 this

  • 생성자 함수가 생성하는 객체로 this 바인딩
  • new 키워드 없이 호출 시 일반 함수 호출과 같아지므로, this가 window에 바인딩
function Person(name) {
  this.name = name;
}
 
var kang = new Person('kang');
var kim = new Person('kim');
 
console.log(kang.name); // kang
console.log(kim.name); // kim


var kang = Person('kang');

console.log(window.name); // kang

 

 

명시적 바인딩 this

  • call(): 첫 번째 인자가 this에 바인딩되고, 두번째 인자부터는 호출한 함수의 파라미터로 사용
  • apply(): call()과 비슷. 첫 번째 인자가 this에 바인딩되고, 두 번째 인자로 배열을 받아 호출한 함수의 파라미터로 사용
  • bind(): this 값 변경 가능. bind()가 호출되면 새로운 함수를 생성하고 첫 번째 인자가 this로 바인딩되고, 두 번째 인자부터는 호출한 함수의 파라미터로 사용

 

차이점

  • call()과 apply()는 this 값을 바꿈과 동시에 함수를 호출
  • bind()는 사용시 호출을 하지 않아 변수에 할당하여 this를 바인딩한 변수를 호출하는 방식으로 사용
var obj = {a: 'Hello'};

var a = 'World';

function show() {
  return this.a;  
}

console.log(show());          // 'World'
console.log(show.call(obj));  // 'Hello'
console.log(show.apply(obj)); // 'Hello'



function add(c, d) {
  return this.a + this.b + c + d;
}

var obj = {a: 1, b: 3};

console.log(add.call(obj, 5, 7)); // 16
console.log(add.apply(obj, [10, 20])); // 34
const person = {
  name: "hjkang",
  age: 30,
};

const get = function(txt){
  console.log(`${this.name} : ${txt}`);
}

const bindGet = get.bind(person, "안녕하세요");
console.log(bindGet()); // hjkang : 안녕하세요

 

 

화살표 함수에서의 this

  • 선언될 시점의 상위 scope
  • 스스로의 this를 가지지 않음
  • 생성될 때 this가 결정되고, 화살표 함수가 어떻게 호출되건 간에 this는 변경되지 않음
  • 객체의 메소드로는 화살표 함수가 아닌 function 함수 사용 필요
const obj = {
  name: "hjkang",
  age: 30,
  get: function() {
    func = () => `${this.name}님은 ${this.age}세 입니다.`;
    console.log(func());
  }
};
console.log(obj.get()); // hjkang님은 30세 입니다.