728x90
1. Input(학습)
- this 란?
- strict모드(this: undefined)
- [JS] 백준 2577번 숫자의 개수
- css-flex
2. Output(복습)
3. Notes(정리)
this
this는 객체다.
this = 자신을 호출한 객체(자신을 가지고 있는 객체)
대부분의 경우 this의 값은 함수를 호출한 방법에 의해 결정된다.(MDN 설명)
예외: 전역스코프(this: window), 화살표 함수(this: 나의 상위 스코프), strict모드(일반 함수의 this: undefined)
1. 일반적인 this 바인딩의 변화 4가지
1. 전역 스코프에서의 this = window(전역 객체)
- 전역 스코프의 일반 함수 내에서 this를 사용하거나
- 그냥 전역 공간에서 console.log(this); 하면 this: window
let user1 = {
name: 'Ryan',
age: 10,
printThis () {
console.log(this);
console.log(user1 === this);
console.log(window === this);
},
};
let printThis = user1.printThis;
printThis();
// Window {window: Window, self: Window, document: document, name: '', location: Location, …}
// false
// true
2. 메서드에서의 this = 자신을 호출한 객체
let user1 = {
name: 'Ryan',
age: 10,
printThis () {
console.log(this);
console.log(user1 === this);
console.log(this.name);
console.log(this.age);
},
};
user1.printThis();
// {name: 'Ryan', age: 10, printThis: ƒ}
// true
// Ryan
// 10
Constructor(생성자 함수), 인스턴스
예를들어 쇼핑몰 사용자의 정보처럼 동일한 프로퍼티 구조를 가진 여러 객체를 만들고 싶은 경우 객체 리터럴 대신 생성자 함수로 객체를 생성하는게 훨씬 더 효율적이다.
- 인스턴스: 생성자 함수에 의해 생성된 객체
3. 생성자 함수 안에서의 this = 인스턴스
function User (name) {
this.name = name; // 인스턴스.프로퍼티(key) = 매개변수(value);
}
const user1 = new User('ryan');
console.log(user1.name); // ryan
4. 이벤트 리스너 안에서의 this = 현재 이벤트가 동작하는 태그(event.currentTarget)
<body>
<button>버튼</button>
<script>
document.querySelector('button').addEventListener('click', function () {
console.log(this);
});
</script>
</body>
<!-- 버튼 클릭시 콘솔창에 <button>버튼</button> 출력된다. -->
2. 복잡한 케이스
2.1 event listener 내에서 콜백함수 사용시의 this = window
- 참고
- 전역 스코프의 일반 함수에서의 this = window
- 객체 내 메서드에서의 this = 자신을 호출한(가지고 있는) 객체
<body>
<button>버튼</button>
<script>
document.querySelector('button').addEventListener('click', function () {
const arr = [1, 2, 3];
arr.forEach(function (num) {
console.log(this);
});
});
</script>
</body>
<!-- 이 경우 this는 window이고 forEach하여 배열의 요소만큼 window가 출력되는 코드이다. -->
2.2 객체 내에서 콜백함수 사용시의 this = window
let obj = {
names: ['김', '나', '박', '이'],
func: function () {
obj.names.forEach(function () {
console.log(this);
});
},
};
obj.func();
2.3 2번 케이스에서 콜백함수를 화살표 함수로 할 경우 this = 상위 스코프
let obj = {
names: ['김', '나', '박', '이'],
func: function () {
obj.names.forEach(() => {
console.log(this);
});
},
};
obj.func();
// this = obj 이므로
// {names: Array(4), func: ƒ}
// {names: Array(4), func: ƒ}
// {names: Array(4), func: ƒ}
// {names: Array(4), func: ƒ} 이렇게 출력됨.
화살표 함수는 내부의 this값을 변화시키지 않는다. 따라서 외부(상위 스코프) this값을 그대로 재사용 가능하다.
4. Reminder
- window(전역 객체)는 전역 공간에서 생성한 변수, 함수 등이 저장되는 공간이다.
// 실제 코드상으론 보이지 않아도 우리는 window객체 내부에서 코딩중임.
// window : {
func1 () {
console.log(this);
}
// }
- 인스턴스: 생성자 함수에 의해 생성된 객체
- display: flex; 를 flex시킬 요소들을 포함하고 있는 부모 요소에 적용
- display: inline-flex; 는 inline-block처럼 보여짐.
- flex-direction: row(행: 가로 방향 정렬), column(열: 세로 방향 정렬), row/column-reverse(~방향으로 역순 정렬)
- flex-wrap:
- nowrap(컨테이너 크기 상관없이 줄바꿈 x)
- wrap(컨테이너 크기 넘어가면 줄바꿈)
- wrap-reverse(컨테이너 크기 넘어갈 시 역순으로 줄바꿈. ex: A,B,C가 C
A,B 처럼 변함)
- justify-content: main-axis 방향 정렬
- flex-start(시작점부터 정렬, 기본값)
- flex-end(끝점부터 정렬)
- center(가운데 정렬)
- space-between(아이템 ‘사이' 균일한 간격 생성)
- space-around(아이템 ‘둘레’에 균일한 간격 생성)
- space-evenly(아이템 ‘사이'와 ‘양 끝’에 균일한 간격 생성)
- align-items: cross-axis 방향 정렬
- stretch(아이템들이 cross-axis 방향으로 늘어남. 기본값)
- flex-start(cross-axis 기준에서 시작점부터 정렬)
- flex-end(cross-axis 기준에서 끝점부터 정렬)
- center(가운데 정렬)
- baseline(텍스트 기준선으로 정렬)
728x90
'기록 > Today I learned' 카테고리의 다른 글
TIL 220408 (0) | 2022.04.08 |
---|---|
TIL 220406 (0) | 2022.04.06 |
TIL 220404 (0) | 2022.04.04 |
TIL 220402 (0) | 2022.04.02 |
TIL- 22.03.22 화 (0) | 2022.03.24 |