this

beomjin_97·2022년 2월 4일
1

javascript

목록 보기
3/13

1. this

자신이 속한 객체 또는 자신이 생성할 인스턴스를 가리키는 자기 참조 변수다.
this를 통해 자신이 속한 객체 또는 자신이 생성할 인스턴스의 프로퍼티나 메서드를 참조 할 수 있다.

// 객체 리터럴

const circle = {
  radius: 5,
  getDiameter() {
    return 2 * this.radius;  //this는 메서드를 호출한 객체를 바인딩
  }
};

console.log(circle.getDiameter()); // 10
// 생성자 함수 

function Circle(radius) {
  this.radius = radius  // this는 생성자 함수가 생성한 인스턴스를 바인딩
}
Circle.prototype.getDiamter = function () {
  return 2 * this.radius;
};

const circle = new Circle(5);
console.log(circle.getDiameter());


2. 함수 호출 방식

this가 가리키는 값, this 바인딩은 함수 호출 방식에 따라 함수 호출 시점에 동적으로 결정된다.

2.1 일반 함수 호출

기본적으로 일반함수로 호출되는 경우 this에는 전역객체가 바인딩된다.
메서드로 정의된 함수나 콜백함수라고 해도 일반함수로 호출 되면 this에는 전역객체가 바인딩된다.
strict mode가 적용된 일반함수 내 this는 undefined가 바인딩 된다.

사실 this는 객체의 프로퍼티나 메서드를 참조하기 위한 자기 참조 변수이므로 일반 함수로 호출시에는 큰 의미가 없다.

2.2 메서드 호출

메서드 내부의 this는 프로퍼티로 메서를 가리키고 있는 객체와는 관계가 없고, 메서드를 호출한 객체에 바인딩된다. (프로토타입 메서드또한 마찬가지다.)

const person = {
  name: 'Lee',
  getName() {
    return this.name:
  }
};

console.log(person.getName());  // Lee

const anotherPerson = {
  name: 'Kim'
}

anotherPerson.getName = person.getName;

console.log(anotherPerson.getName()); // Kim

2.3 생성자 함수 호출

생성자 함수의 내부의 this에는 생성하 함수가 생성할 인스턴스가 바인딩 된다.

function Circle(radius) {
  this.radius = radius;
  this.getDiameter = function () {
    return 2 * this.radius;
  }
}

const circle1 = new Circle(5);
const circle2 = new Circle(10);

console.log(circle1.getDiameter());  // 10
console.log(circle2.getDiameter());  // 20

2.4 간접 호출

apply, call, bind 메서드는 Function.prototype의 메서드이다. 따라서 모든 함수가 상속받아서 사용할 수 있다.

2.4.1 apply, call

apply와 call 메서드는 this로 사용할 객체와 인수 리스트를 인수로 전달 받아 함수를 호출한다.
호출할 함수의 인수를 전달하는 방식만 다를 뿐 동일하게 동작한다.

function getThisBinding() {
  console.log(arguments)
  return this;
}

const thisArg = {a: 1}  // this로 사용할 객체

console.log(getThisBinding.apply(thisArg, [1, 2, 3]))
console.log(getThisBinding.call(thisArg, 1, 2, 3))

2.4.2 bind

bind 메서드는 함수를 호출하지 않는다. 첫번째 인수로 전달한 값으로 this 바인딩이 교체된 함수를 새롭게 생성해 반환한다.

function getThisBinding() {
  return this
}

const thisArg = {a: 1}

console.log(getThisBinding.bind(thisArg())); // 함수를 호출하지 않기 때문에 명시적으로 호출해야 한다.
profile
Rather be dead than cool.

0개의 댓글