[JavaScript] 자바스크립트의 this

Tech/JavaScript & TypeScript 2023. 1. 13. 22:16
728x90
728x90

this


자바의 this와는 다르게 클래스에 종속되지 않으며 자바스크립트에서의 this는 함수의 호출방식에 따라 가져오는 객체가 달라지므로 this의 사용 위치가 중요하다.

기본적으로는 최상위객체인 window를 가리킨다.

console.log(this);                      // window
function test1(){
    console.log("test1 ", this);        // test1 window
    function test2(){
        console.log("test2 ", this);    // test2 window
    }
    test2();
}
test1();

 

 

 

 

함수 안에서의 this

함수 안에서의 this는 함수의 주인에게 바인딩된다.

아래의 예시에서 this.num의 this는 window객체를 가리킨다.

var num = 0;
function addNum() {
  this.num = 100;
  num++;
  
  console.log(num);                // 101
  console.log(window.num);         // 101
  console.log(num === window.num); // true
}
 
addNum();

 

 

 

메서드 안에서의 this

메서드 내부 코드에서 사용된 this는 해당 메서드를 호출한 객체로 바인딩된다.

var person = {
  firstName: 'Hong',
  lastName: 'gildong',
  fullName: function () {
    return this.firstName + ' ' + this.lastName;
  },
};
 
person.fullName(); // "Hong gildong"
var num = 0;
 
function showNum() {
  console.log(this.num);
}
 
showNum(); // 0
 
var obj = {
  num: 7,
  func: showNum,
};
 
obj.func(); // 7

 

 

 

이벤트 핸들러 안에서의 this

이벤트를 받는 html요소를 가리킨다.

const btn = document.querySelector('#btn')
btn.addEventListener('click', function () {
  console.log(this); //#btn
});

 

 

 

생성자 안에서의  this

생성자 함수가 생성하는 객체로 바인딩된다.

function Person(name) {
  this.name = name;
}
 
var kim = new Person('kim');
var lee = new Person('lee');
 
console.log(kim.name); //kim
console.log(lee.name); //lee

 

 

 

화살표 함수(Arrow function)에서의  this

함수 안에서 this가 전역 객체가 되는 경우, 화살표 함수로 사용하면 된다.

화살표 함수는 this를 새로 정의하지 않고, 바로 바깥 함수나 클래스의 this를 사용한다.

var Person = function (name, age) {
  this.name = name;
  this.age = age;
  this.say = function () {
    console.log(this); // Person {name: "Nana", age: 28}
 
    setTimeout(function () {
      console.log(this); // Window
      console.log(this.name + ' is ' + this.age + ' years old');
    }, 100);
  };
};
var me = new Person('Nana', 28);
 
me.say(); //global is undefined years old
var Person = function (name, age) {
  this.name = name;
  this.age = age;
  this.say = function () {
    console.log(this); // Person {name: "Nana", age: 28}
 
    setTimeout(() => {
      console.log(this); // Person {name: "Nana", age: 28}
      console.log(this.name + ' is ' + this.age + ' years old'); 
    }, 100);
  };
};
var me = new Person('Nana', 28); //Nana is 28 years old

 

 

 

 

참조 ( 정말 많은부분 배웠습니다 감사합니다 )

https://nykim.work/71

728x90
300x250
mag1c

mag1c

2년차 주니어 개발자.

방명록