220811.til

Universe·2022년 8월 11일
0

study

목록 보기
24/49

서론

리엑트를 시작하기 전에 자바스크립트에 대한 깊이가 조금 모자란다고 생각이 되어
ES6 문법과 함께 배열, 오브젝트 활용법을 반드시 짚고 넘어가야겠다고 생각했다
그도 그럴게, 프로젝트를 진행하면서도 종종 나오는
동기 / 비동기 개념이라던가 fetch 는 promise 를 반환한다던가
prototype 에 관련된 개념이라던가 모르는 부분이 너무 많았다
배열에 관한 부분에서도 map, filter, forEach 메서드를 잘 활용하지 못해
for문을 사용한다거나 하는 부분이 계속 신경쓰였다
공부에는 시기가 있다고 배웠다
지금 제대로 기초를 다져놓아야 나중에 다른개념을 배워도 활용할 수 있을 것 같았다





this - keyword

this 의 특성에 대해서 알아보자

1. { window }

console.log(this);

function 함수(){
  console.log(this;
}

=
// Window {0: Window, window: Window, self: Window, document: document, name: '', location: Location, …}
// Window {0: Window, window: Window, self: Window, document: document, name: '', location: Location, …}

전역에서 사용하거나 일반 함수 안에서 사용하면 {window} 라는 오브젝트를 반환한다

{window} : 자바스크립트 기본 함수들을 가지고 있는 오브젝트

‘use strict;’ - 자바스크립트 엄격모드

엄격모드 off
x = 300 (o)
var x = 300 (o)

엄격모드 on
x = 300 (x)
var x = 300 (o)

‘use strict’ 옵션을 활성화하면 ?

console.log(this);

function 함수(){
  console.log(this;
}

=
// Window {0: Window, window: Window, self: Window, document: document, name: '', location: Location, …}
// undefined

2. 오브젝트 / 메소드 안에서의 this

var object = {
	data : 'kim',
    func : function(){
      console.log(this)
  }
}

object.func();

// {data: 'kim', func: ƒ}

오브젝트, 메소드 내 함수안에서의 this는 : 해당 함수를 가지고 있는 오브젝트를 리턴한다

그러면 오브젝트 안에 오브젝트, 그 안에 this가 있으면 ?

var object = {
  data : {
    func : function(){
      console.log(this)
    }
  }
}

object.data.func();

// {func: ƒ} === object.data

마찬가지로 그 함수를 가지고 있는 오브젝트를 리턴한다

같은 오브젝트를 arrow function 으로 구현한다면 ?

var object = {
  data : {
    func : () => {
      console.log(this)
    }
  }
}

object.data.func();

// Window {0: Window, window: Window, self: Window, document: document, name: '', location: Location, …}

arrow function 은 this 값을 함수 밖에 있던거 그대로 쓴다

! ES6 객체 신 문법

var object = {
 data : {
//    func : () => {
			func(){
     console.log(this)
   }
 }
}

오브젝트 안에 함수를 사용할 때에는 function 키워드를 생략할 수 있다



1번개념과 2번개념은은 사실 똑같은 개념이다
자바스크립트의 전역공간에서 함수나 변수를 선언하면
{window} 라는 객체 안에 보관하게 되어있다 (global object)
따라서 전역변수 취급을 받는 대상은 this 를 호출했을 때 window 를 리턴하는 것이다



3. constructor 안에서 쓰는 this

오브젝트 생성기계 (constructor)

function constructor(e) {
  this.name = e
}

var obj = new constructor('철수');
console.log(obj)

// constructor {name: '철수'}

여기서의 this 는 새로 생성되는 오브젝트 (instance) 를 뜻한다



4. addEventListener 안에서 쓰는 this

document.getElementById('button').addEventListener('click', function(e){
	this;
	// = e.currentTarget;
	// = document.getElementById('button')
    // = 해당 버튼을 의미한다
})

지금 이벤트가 동작하고 있는 HTML 요소

5. 그렇다면…

document.getElementById('button').addEventListener('click', function(){
	var arr = [1,2,3];
	arr.forEach(function(){
  console.log(this};
})

이 경우의 this 는 어떤 값을 출력하게 될까 ?
forEach 내부의 콜백함수는 전역으로 취급되므로
{window} 를 리턴하게 된다

var obj = {
  name : ['kim', 'lee', 'pack'],
  func : function(){
    console.log(this) // 1번
    obj.name.forEach(function(){
    console.log(this) // 2번
    })
  }
}

obj.func();

그럼 오브젝트 내에서 콜백함수를 쓴다면 this 값은 ?

// 1번 출력결과
name: Array(3), func: ƒ}

// 2번 출력결과
Window {0: global, 1: global, 2: global, window: Window, self: Window, document: document, name: '', location: Location,}
Window {0: global, 1: global, 2: global, window: Window, self: Window, document: document, name: '', location: Location,}
Window {0: global, 1: global, 2: global, window: Window, self: Window, document: document, name: '', location: Location,}

1번의 경우 오브젝트 내에서의 this 라서 오브젝트 값을 리턴하지만,
2번의 경우 전역취급되는 일반함수이므로 3번의 {window} 를 리턴한다

var obj = {
  name : ['kim', 'lee', 'pack'],
  func : function(){
    console.log(this) // 1번
    obj.name.forEach(() => {
    console.log(this) // 2번
    })
  }
}

obj.func();

그럼 function 를 arrow function 으로 변경한다면 ?

{name: Array(3), func: ƒ}
{name: Array(3), func: ƒ}
{name: Array(3), func: ƒ}
{name: Array(3), func: ƒ}

arrow function 은 내부의 this 값을 변경시키지 않고
외부 this 값을 그대로 사용하기 때문에 오브젝트 값을 리턴하게 된다





총평

알고 있다고 생각했던 개념이 '사실을 이렇다' 라는 것을 알게됐을때,
혹은 '그 개념은 사실은 이것때문이다' 라는 것을 알게됐을때가 제일 재밌다고 생각한다.
오늘은 정말 그런날이었다.
arrow function 같은 경우에는
this 도 제대로 안담기는 그냥 예쁘게 쓰려고 만든 문법인가? 하고 이해했지만
오히려 function 을 대체하는 문법이 아니고 제대로 된 쓸모를 가진 아이였다.
this 개념을 제대로 알지도 못하고
어떤 경우에는 window 가 호출되고 어떤 경우에는 querySelector 같이 호출되는
이상한 문법이라고 생각했다.
처음 자바스크립트를 배웠을 때의 느낌이 들어 새롭고 신선하고 재밌었다.
🥳

profile
Always, we are friend 🧡

0개의 댓글