THIS

Bruce·2021년 8월 18일

프론트엔드 코어

목록 보기
6/31

this

일반적으로 메소드를 호출한 객체의 정보가 저장되어 있는 속성.

케이스에 따른 this가 가르키는 것.

전역공간: window/global####

console.log(this)
// Window {0: global, 1: global, 2: global, window: Window, …}

함수: window/global(strict모드일때 함수의 this는 undefined)

function outer() {
    console.log(this);
}
outer();
// Window {0: global, 1: global, 2: global, window: Window, …}

서브루틴(메서드가 아닌 함수): window/global

function outer() {
    function inner() {
        console.log(this);
    }
    inner();
}
outer();
// Window {0: global, 1: global, 2: global, window: Window, …}

메소드: 메소드 호출 주체

const foo = {
    name: 'bear',
    honey: function() {
        console.log(this.name, this);
    }
}
foo.honey();
// bear {name: 'bear', honey: ƒ}

콜백: window/global(그러나 call, apply, bind로 this를 바인딩 가능.)

function one(callback) {
    console.log(callback())
}
function two() {
    console.log(this)
}
one(two)
// Window {window: Window, self: Window, …}

생성자함수: 인스턴스

function User(name) {
    this.name = name;
    this.speak = function() {
        console.log('hello! '+this.name, this);
    }
}
const getChris = new User('chris');
const getAnne = new User('anne');
getChris.speak();
getAnne.speak();
// hello! chris User {name: 'chris', speak: ƒ}
// hello! anne User {name: 'anne', speak: ƒ}
profile
Figure it out yourself

0개의 댓글