본문 바로가기

Node.JS

[인간 JS엔진 되기] 1-6. this

 

 

 

 

ES2015 모듈에서는 strict 모드 자동 적용됨
function a() {
    //'use strict'; //만약 strict 모드를 사용을 위해 주석을 풀면, this는 undefined가 됨
    console.log(this);
}

//a()

console.log(globalThis)

//브라우저 js 의 전역은 window, 최근에 업데이트되어서 window가 globalThis 로 바뀜
// node 의 전역은 global, node도 global이 globalThis로 바뀜

 

 

 

this는 어디서 호출하느냐에 따라 달라짐

obj 안에서 this는 obj

하지만 sayN에 obj.sayName을 대입하고

sayN을 호출하면 this가 바뀜

this 는 함수가 호출 될 때 결정됨. 함수를 전역 스코프에서 호출하면 global이 this가 되고

객체에서 호출하면 this는 호출한 객체가 될 것임

const obj = {
    name:'zerocho',
    sayName() {
        console.log(this.name);
    }
}

obj.sayName() //zerocho


const sayN = obj.sayName;
sayN() //undefined

 

또한 obj의 sayName이 화살표 함수면 this는 달라짐

화살표 함수로 선언하면 부모의 this를 물려받음

 

const obj = {
    name:'zerocho',
    sayName:()=> {
        console.log(this.name);
    }
}

obj.sayName() //undefined

 

 

function Human (name) {
    this.name = name;
}

const xxx = new Human('zerocho')
console.log(xxx.name) //zerocho
console.log(new Human('zerocho').name) //위와 같음 zerocho

 

아래의 스코프 체인은

inner -> sayName -> anonymous

 

첫번째 this는 obj3.sayName()에 의해 실행되므로 this는 obj3

 

두번째 this는 inner 함수가 그 자체로 호출되므로 this는 global임

 

const obj3 = {
    name:'zerocho',
    sayName(){
        console.log(this.name);// zerocho
        function inner() {
            console.log(this.name)//undefined
        }
        inner();
    }
}

obj3.sayName()

화살표 함수로 하면 this는 함수가 속한 스코프의  this로 정의됨

const obj3 = {
    name:'zerocho',
    sayName(){
        console.log(this.name);// zerocho
        const inner=()=> {
            console.log(this.name)//zerocho
        }
        inner();
    }
}

obj3.sayName()

 

this는 호출하는 방법에 따라 결정됨!