22장. this

Happhee·2021년 12월 9일
0

JS : Depp Dive

목록 보기
19/35
post-thumbnail

1. this 키워드

객체는 상태를 나타내는 프로퍼티와 동작을 나타내는 메서드를 하나로 묶은 복합적인 자료구조
메서드가 자신의 객체의 프로퍼티를 참조하려면 자신이 속한 객체를 가리키는 식별자를 참조할 수 있어야 함

  • this
    자신이 속한 객체 또는 자신이 생성할 인스턴스를 가리키는 자기 참조 변수

  • this 바인딩
    식별자와 값을 연결
    함수 호출 방식에 의해 동적으로 결정


2. 함수 호출 방식과 this 바인딩

this 바인딩은 함수 호출 방식
함수가 어떻게 호출되었는지에 따라 동적으로 결정

  • 렉시컬 스코프
    함수 정의가 평가되어 함수 객체가 생성되는 시점에 상위 스코프를 결정

  • this 바인딩
    함수 호출 시점에 결정

1. 일반 함수 호출

  • 일반적으로 전역 객체 바인딩
    • 중첩함수, 콜백 함수로 호출된 모든 일반함수
    • 참조하려면 that 사용!
  • strict mode를 적용 -> undefined
var value = 1;

const obj = {
    value: 100,
    foo() {
        //콜백함수에 this 바인딩
        setTimeout(function () {
            console.log(this.value);
        }.bind(this), 100);
    }
};

obj.foo();

2. 메서드 호출

const person = {
    name: 'seohee',
    getName() {
        return this.name;
    }
}
const another = {
    name: 'jc'
};
another.getName = person.getName;
console.log(another.getName());
const funcGetName = person.getName;
console.log(funcGetName());

3. 생성자 함수 호출

function Circle(rad) {
    this.rad = rad;

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

const c1 = new Circle(3);
const c2 = new Circle(9);

console.log(c1.getDiameter());
console.log(c2.getDiameter());

반드시 new 연산자와 함께 호출해야함

4. Function.prototype.apply/call/bind 메서드에 의한 간접 호출

  • apply 와 call 메서드의 본질적인 기능은 함수를 호출하는 것
profile
즐기면서 정확하게 나아가는 웹프론트엔드 개발자 https://happhee-dev.tistory.com/ 로 이전하였습니다

0개의 댓글