JS This

gang_shik·2025년 3월 19일
0

JavaScript

목록 보기
15/23

This란?

  • this는 스코프와 관계가 있음, JS는 함수, 배열, 일반적인 객체를 다 객체로 보는데, this가 어디에 묶여있는지를 아는 것에 따라서 처리하고 활용도가 다름
  • this가 의도와 다르게 호출되고 동작할 수 있기에 bind 메소드를 활용해서 처리하는 경우도 있음
  • 참고자료

암시적 바인딩

  • NodeJS 환경에서 전역 객체는 Global이고 브라우저에서 객체는 window 객체임, 하지만 this는 또 다르게 적용함
  • 그리고 함수 공간에서의 this도 다름, this가 전역공간을 바라보기에 여기선 브라우저도 window가 됨
  • 객체에서의 this는 객체 내 메서드에서의 호출되는 대상의 객체를 바라봄
const obj2 = {
  name: 'obj',
  depth: {
    name: 'nested obj',
    method: function() {
      return this.name
    }
  }
}

obj2.depth.method() // nested obj를 불러옴(호출된 대상의 this를 불러옴)
  • 이를 안전하게 만들어주는 것을 명시적인 바인딩으로 this를 묶어줌(함수라고 해서 무조건 전역공간을 바라보지 않기 때문임)

명시적 바인딩

  • call, apply, bind 내장 메소드를 통해서 this를 명시적으로 바인딩 할 수 있음
  • JS에서는 var 키워드를 쓰면 전역 객체로 들어가버리기에 const로 예시를 썼음
  • 아래와 같은 케이스에서 function을 쓰려고 할 때, 명시적인 바인딩을 통해서 this의 바운더리를 정해서 함수를 선택해서 쓸 수 있음
const person = {
  name: 'Kevin',
  sayName: function() {
    return this.name + '입니다';
  },
};

const zero = {
  name: 'Base',
  sayName: function() {
    return this.name + '입니다';
  },
};

function sayFullName(firstName) {
  return firstName + this.sayName()
}

// call 메서드로 인해 person 객체의 this를 사용해서 쓸 수 있음
const result = sayFullName.call(person, 'Hart');
// call 메서드로 인해 zero 객체의 this를 사용해서 쓸 수 있음
const result2 = sayFullName.call(zero, 'Oh');

// apply 메서드에서의 배열로 받은 인자를 arguments를 통해 배열 요소로 값을 쓸 수 있음
function sayFullName(firstName) {
  return arguments[0] + this.sayName() // arguments[1] + this.sayName();
}

// apply 메서드는 배열을 인자로 받아서 쓸 수 있음, call과 사용성은 다른게 없음(원하는 객체의 this를 쓰기 위함)
const result3 = sayFullName.apply(person, ['Oh', 'Kim']);
const result4 = sayFullName.apply(zero, ['Zero', 'Base']);


function sayFullName(firstName) {
  return firstName + this.sayName()
}

// bind 메서드를 통해서, 직접적으로 객체에 연결하고 아래와 같이 씀으로써 바로 this를 명시적으로 처리할 수 있음
const sayFullNamePerson = sayFullName.bind(person);
const sayFullNameZero = sayFullName.bind(zero);

console.log(sayFullNamePerson('oh'));
console.log(sayFullNameZero('zero'));
profile
측정할 수 없으면 관리할 수 없고, 관리할 수 없으면 개선시킬 수도 없다

0개의 댓글