[JS] this는 무엇일까?

양성진·2022년 7월 8일
0

JS

목록 보기
5/5

this는 뭘까?

코드에 짜여진 함수를 볼때 this를 많이 쓰는걸 볼수가 있다.

this란 뭘까? 공식문서에 나온 내용을 보면

대부분의 경우 this의 값은 함수를 호출한 방법에 의해 결정한다고 한다.

그래서 실행중엔 할당이 안되고 쓰임새도 호출할때마다 다 다르다.

this의 쓰임새

  • node.js에서는 this는 글로벌
  • 전역 공간에서 this -> window의 역할을 한다.
  • 함수에서의 this-> window의 역할, 즉 전역공간을 가르킨다.
  • 객체의 this -> 메서드(Method)의 역할을 한다.
const obj2 = {
    name:'obj',
    depth:{
        name:'nexsted obj',
        method:function(){
            return this.name
        }
    }
}

console.log(obj2.depth.method()) // output:nexted obj

그래서 이렇게 상황에 따라 this가 바인딩이 되는걸 암시적인 This 바인딩이라 부른다. 이렇게 암시적으로 상황에 따라 바뀌면 불확실하기도 해서 암시적인것을 명시적 바인딩을 할수 있는 방법이 있다.

appply(),bind(),call()를 이용해보면 된다.

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

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


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

const result = sayFullName.call(person,'양')
// // apply() 배열로 파라미터를 받을수 있음
const result2 = sayFullName.apply(zero,['Yang','zero'])
console.log(result) 양 성진입니다
console.log(result2) // -> sayFullName의 arguments가 [0]일땐 Yang베이스 입니다로 출력


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

function sayFullName(firstName){
    return firstName + this.sayName();
};
console.log(sayFullNamePerson('장'));
console.log(sayFullNameZero('제로'));
console.log(sayFullNamePerson('장'));

apply()와 call() 하는 행동은 같지만 전자는 배열로 받을수 있고 후자는 그렇게 할수 없다. bind()는 메소드가 호출되면 새로운 함수를 생성을 한다.

profile
프론트엔드 개발자를 꿈꾸는 돼지

0개의 댓글

관련 채용 정보