this란 무엇인가

Steve·2021년 4월 23일
1

자바스크립트에서 항상 들리는 단어.this
오늘 한 번 제대로 정리하고 넘어가 보자

this
dot(.)이 있느냐 없느냐로 구분된다.라고 듣고 일단 시작하자
무슨말인고 하니 코드로 보여보겠다.

let vv = 23;
vv = function test1(x) {
  console.log(123*x);
  return "aaa";
}

let ddd = vv(2); // vv함수는 호출됐기 대문에 246출력됐고, 반환된 "aaa"를 ddd에 할당
console.log(ddd); // aaa

객체 안의 프로퍼티 넣는 방법

  • key : value 그리고 쉼표(,)
let oo = {
  oo2 : {
    country : "Korea",
    date : "July"
  },
  oo3 : ['sunglasses', 'pants', 'bag'],
  name : 'steve',
  age : 20,
  eat : function() {
    console.log(this);
    console.log('delicious');
    return 'WOW';
  }
};
console.log(oo.name); // steve
console.log(oo.oo2.country); // 객체안의 객체안의 프로퍼티 출력 Korea
console.log(oo.oo3[2]); // 객체안의 프로퍼티의 값이 배열. 2번째 출력
console.log(oo.eat()); // 리턴값 'WOW' . 리턴값 안적으면 undefined
    
     

this, bind

함수를 호출한 객체를 this라고 한다.
함수에는 bind함수가 내장돼있다.

  let oo = {
  	name : "abcd",
    kk : {
      ee : function() {
        console.log(this);
      },
      cc: { // cc 는 오브젝트이다. 그래서 bind함수가 없음
        dd : function() { // dd는 함수이다. bind함수가 있다.
          console.log(this);
        }
      }
    }
  };


let ff = oo.kk.cc.dd.bind(123); // 새롭게 리턴한 dd함수를 ff에 할당(리턴된 새로운 함수의 this의 값은 123으로 고정됨)
oo.kk.cc.ee = ff; //cc객체 안에 새롭게 ee함수 추가. ff는 함수인 상태
oo.kk.cc.dd(); // oo.kk.cc가 this
oo.kk.cc.ee(); // 함수 실행. this는 123

예제)

profile
Front-Dev

0개의 댓글