This - binding 기본

JA_X·2023년 6월 1일
0

암시적 바인딩

암시적 바인딩은 JavaScript에서 함수 호출 시 암시적으로 this가 어떤 객체에 바인딩되는 것을 의미합니다. 이는 호출한 위치나 메소드를 호출한 객체에 의해 결정됩니다.

  • 암시적 바인딩 규칙
  1. 전역 공간:
    전역 공간에서 함수를 호출하면, this는 전역 객체 (브라우저에서는 window, Node.js에서는 global)에 암시적으로 바인딩됩니다.
function greet() {
  console.log(`Hello, ${this.name}!`);
}

name = 'Alice';
greet(); // 출력: "Hello, Alice!" (전역 객체에 name 프로퍼티를 설정해야 합니다.)
  1. 메소드 호출:
    메소드 내에서의 함수 호출 시, 해당 메소드를 소유한 객체가 this로 암시적으로 바인딩됩니다.
    함수가 객체의 프로퍼티로 호출되면, this는 해당 객체에 바인딩됩니다.
const person = {
  name: 'Alice',
  greet: function() {
    console.log(`Hello, ${this.name}!`);
  }
};

person.greet(); // 출력: "Hello, Alice!"
  1. 객체 내부 함수:
    객체 내부에 정의된 함수에서도 해당 객체가 this로 암시적으로 바인딩됩니다.
    그러나 중첩된 함수의 경우에는 해당 객체가 this로 바인딩되지 않습니다.
const person = {
  name: 'Alice',
  greet: function() {
    const innerFunction = function() {
      console.log(`Hello, ${this.name}!`);
    };
    // greet 메소드(함수)를 호출해도 중첩함수에서는 this가 해당객체에 바인딩되지 않은 상황
    innerFunction(); // 출력: "Hello, !"
  }
};

person.greet();

암시적 바인딩은 함수 호출 시 this를 결정하는 유용한 규칙 중 하나입니다. 객체의 메소드에서 this를 사용하여 해당 객체의 프로퍼티에 접근하거나 조작할 수 있습니다.

그러나 중첩된 함수의 경우 암시적 바인딩이 원하는 대상을 가리키지 않을 수 있으므로 편의를 위해 명시적으로 this를 바인딩해주는 방법이 존재한다!

명시적 바인딩

JavaScript에서 call, apply, bind는 함수의 this 바인딩을 제어하기 위해 사용되는 메소드입니다.

/*

명시적 바인딩

1. call
2. apply
3. bind

*/

const person = {
  name: "재성",
  sayName: function () {
    return this.name + "입니다";
  },
};

const zero = {
  name: "베이스",
  sayName: function () {
    return this.name + "입니다";
  },
};

// 1. call

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

// call 을 사용하여 첫 번째 인자로 받는 객체에 this를 바인딩 한다.

const result = sayFullName.call(person, "이");
const result2 = sayFullName.call(zero, "제로");

console.log(result); // 이재성입니다
console.log(result2); // 제로베이스입니다

// 2. apply

function sayFullName2(firstName) {
  return arguments[1] + this.sayName();
}

// apply는 call 과 기본적인 동작은 같지만 인자를 배열 형태로 받아 쓸 수 있다.

const result3 = sayFullName2.apply(person, ["이", "Lee"]);
const result4 = sayFullName2.apply(zero, ["제로", "Zero"]);

console.log(result3); // Lee재성입니다
console.log(result4); // Zero베이스입니다

// 3. bind

// 인자로 받은 받은 객체로 바인딩 된다.
// call, apply 와 다르게 객체를 바인딩하고 즉시 호출하는게 아니라
// binding 상태를 유지하고 추후에 호출할 수 있다.

const sayFullNamePerson = sayFullName.bind(person);
const sayFullNameZero = sayFullName.bind(zero);

console.log(sayFullNamePerson("이")); // 이재성입니다
console.log(sayFullNameZero("제로")); // 제로베이스입니다

이외에 this 바인딩과 관련된 화살표 함수는 자신만의 'this'를 가지지 않는다를 이용하는 방법과,
외부함수에서 self 변수에 this를 할당하여 중첩함수 내에서 this를 바인딩시키는 방법 등은
다음 편에 계속...

0개의 댓글