알랑말랑한 브라우저 환경에서의 this

binary·2022년 5월 16일
2
post-thumbnail

👉 this

  • JavaScript 예약어

  • 자기 참조 변수(self-reference variable)

  • 보통 객체의 메서드 내부 또는 생성자 함수 내부에서 쓰인다

🤯 상황에 따라 달라지는 this

브라우저 환경으로 한정하여 정리한 내용입니다.

nods.js 환경 등 다른 환경에서는 또 다른 일들이 벌어집니다!

🌟 전역에서의 this

this;

window 전역 객체를 참조한다.

  • 👩‍💻 결과

🌟 함수 안에서의 this

function fn() {
	console.log(this);
}

fn(); // window

window 전역 객체를 참조한다.

  • strict 모드일 경우
    'use strict';
    
    function fn() {
    	console.log(this);
    }
    
    fn(); // undefined
    undefined

🌟 화살표 함수 안에서의 this

const foo = {
  name: 'cat',
  callName: () => console.log(this),// window
}

화살표 함수의 this 는 상위 환경의 this 를 참조한다.

위와 같은 경우는 상위 환경이 전역이기 때문에 전역 객체를 가리키게 된 것이다.

  • 👩‍💻 결과

🌟 addEventListener 함수의 콜백 함수의 this

const button = document.querySelector(".btn");

button.addEventListener("click", () => {
	console.log(this); // window
});

콜백 함수가 화살표 함수로 작성되어 this 가 전역 객체 window 를 가리킨다.

  • 👩‍💻 결과

🌟 객체의 메서드 안에서의 this

const obj = {
	fn: function() {
		console.log("this", this);
	}
}

obj.fn(); // obj
  • 👩‍💻 결과

객체의 메서드를 호출할 때 this 를 내부적으로 바꿔준다.

❗️ 비슷한 듯 다른 상황

const obj = {
	fn: function() {
		console.log("this", this);
	}
}

obj.fn(); // obj

const fn2 = obj.fn;
fn2(); // window
  • 👩‍💻 결과

fn2() 의 결과가 obj 가 아닌 이유는 fn2 이라는 변수에 obj.fn 을 값으로 할당했기 때문에 obj의 메서드가 아닌 그냥 함수이다.

함수 안에서 사용하는 thiswindow 를 가리키기 때문에 fn2window 를 가리킨다.


❓ bind(), call(), apply() 를 사용하면 this 는 어떻게 될까?

  • bind() 메소드func.bind(thisArg[, arg1[, arg2[, ...]]]) 의 형태로 사용한다.
    • 함수 functhisthisArg 로 전달하여 원본 함수의 복제본을 반환한다.
    • 📖 예제
      const obj = {
          name: "cat",
      }
      
      function func() {
        console.log("func의 this" , this);
      };
      
      // func 함수의 this 를 obj 로 전달한 함수를 funcUser라는 변수에 할당
      let funcUser = func.bind(obj);
      
      funcUser(); // obj
  • call() 메소드func.call(thisArg[, arg1[, arg2[, ...]]]) 의 형태로 사용한다.
    • 매개변수는 선택사항
    • func 라는 함수의 this 를 누구로 변경할 건지 설정할 수 있다.
    • func.call(객체, 인자값);
    • 📖 예제
      const obj1 = {
          name: "cat",
          func : function() {
              console.log("name은", this.name);
      				console.log(this);
          }
      }
      
      obj1.func(); // name은 cat
      
      const obj2 =  {
          name: "dog",
      		func : function() {
              console.log("좋아하는 동물은", this.name);
          }
      }
      
      obj2.func(); // 좋아하는 동물은 dog
      obj1.func.call(obj2); // name은 dog
  • apply() 메서드func.call(thisArg[, arg1[, arg2[, ...]]]) 의 형태로 사용한다.
    • call() 메서드와 비슷한데 인자값만 다르다.
    • func.call(객체, 인자값 배열);
    • 📖 예제
      function get(a, b) {
        console.log(a + b + arguments[2]);
      }
      
      get.apply(this, [10, 20, 30]); // 60
      
      var obj = {
        value: 123,
        nestedObj: {
          value: 456,
          get: function (a, b) {
            console.log(a + " " + b + " " + this.value + " " + arguments[2]);
          },
        },
      };
      
      obj.nestedObj.get.apply(obj, [1, 2, 3]); // 1 2 123 3
      obj.nestedObj.get.apply(obj.nestedObj, [1, 2, 3]); // 1 2 456 3

혹시나 잘못된 정보가 있다면 댓글로 알려주세요 ! 저의 성장의 큰 도움이 될 것 같습니다.🌱

2개의 댓글

comment-user-thumbnail
2022년 5월 21일

🙋‍♂️ 브라우저 환경이 아닌 node.js 환경이라면 window 전역 객체를 참조하지 않고 global 객체를 참조할 것 같아요.
도입부에 브라우저 환경에서의 내용이라는걸 명시해주면 더 좋을 것 같습니다 👍

1개의 답글