Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

14, 15장 정리 #6

Merged
merged 2 commits into from
Nov 16, 2024
Merged

14, 15장 정리 #6

merged 2 commits into from
Nov 16, 2024

Conversation

junepil
Copy link
Collaborator

@junepil junepil commented Nov 12, 2024

What's new?

  • 전역 변수에 대해 정리했습니다.
  • ES6에서 도입된 let, const 키워드에 대해 정리했습니다.

날로 먹는 단원이라 맛있네요 😋

Copy link
Member

@Turtle-Hwan Turtle-Hwan left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

고생하셨습니다

Comment on lines +64 to +79
나중에 설명할 **클로저**를 이용해 관련 있는 변수와 함수들을 IIFE로 감싸 모듈을 만드는 방법이다.
```javascript
var Counter = (function () {
var num = 0;

return {
increase() {
return ++num;
},
decrease() {
return --num;
}
}
})
```
위의 예시에서 `num`은 반환값에 포함되어 있지 않기 때문에 직접 접근할 수 없지만 `Counter.increase()`. `Counter.decrease()` 메소드를 이용해 `num`의 값을 수정할 수 있다.
Copy link
Member

@Turtle-Hwan Turtle-Hwan Nov 12, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

클로저가 함수형 프로그래밍의 특징이고, 이 예시는 마치 객체지향에서 setter를 사용하는 느낌이네요

Co-authored-by: 김지환 (Jihwan Kim) <kjhwan0802@naver.com>
Copy link
Member

@zziglet zziglet left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

고생 많으셨습니다아 🍥

Comment on lines +45 to +55
## 14.3.1 즉시 실행 함수
모든 코드를 IIFE로 감싸 즉시 실행 함수의 지역 변수로 만드는 방법이다.
```javascript
(function() {
var foo = 10;
// ...
}());

console.log(foo); // ReferenceError: foo is not defined
```
> 이런 코드가 진짜로 사용되나요? 전 한 번도 못 봤어요..
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

12장 pr에서도 논란이 많았던 즉시 실행 함수...계속해서 등장하네요

Comment on lines +56 to +62
## 14.3.2 네임스페이스 객체
전역 네임스페이스 객체를 생성하고 해당 객체에 사용하고 싶은 변수를 프로퍼티로 추가하는 방법이다.
```javascript
var MYAPP = {};

MYAPP.name = 'Lee';
```
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

네임스페이스 안에 또다른 부분적인? 네임스페이스도 생성할 수 있으니까... 계층적으로 관리할 수 있는 느낌도 가질 수 있는 것일까오

Comment on lines +94 to +95
# 15.4 var vs. let vs. const
`var`를 쓰지 말고 `let`과`const`를 애용하도록 하자. 지역 스코프 관리, 재할당 문제 등에서 ES6에서부터 도입된 `let`, `const`를 사용하는게 좋다.
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

15장은 약간 지금까지 한 얘기 총집합 느낌도 있네요

Copy link
Member

@MinboyKim MinboyKim left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

고생하셨습니다~ 지난 내용들 좀 돌이켜보는 것 같기도 하고 쉬어가는 느낌이네요 🐧

- 암묵적 결합: 전역 번수는 코드의 모든 곳에서 참조하고 수정할 수 있기 때문에 코드의 가독성이 나빠지고 예기치 못한 상황에서 값이 변경되는 결과를 초래한다.
- 긴 생명 주기: 긴 생명 주기를 가지기 때문에 자원또한 지역 변수보다 많이 소모한다.
- 스코프 체인 상에서 가장 긴 거리: 스코프 체이닝을 통해 식별자를 찾는 과정에서 가장 마지막에 검색되기 때문에 검색 속도가 느리다.
- 네임스페이스 오염: 여러 파일이 하나의 전역 스코프를 공유하기 때문에 다른 파일에서 서로 같은 이름으로 전역 변수를 선언할 경우 예상치 못한 결과가 발생할 수 있다.
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

여러 파일이 하나의 전역 스코프를 공유한다는 것,,
참 중요한 것 같아요

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

다른 파일이면 다른 스코프라 생각할 수 있지만, 실제론 같은 스코프일 수 있어 주의!
ES6 이후부터는 import로 불러오므로 다른 파일은 다른 스코프이다!

`const`로 선언된 변수는 값을 재할당할 수 없다.
```js
const foo = 1;
foo = 2; // TypeError
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

https://futurecreator.github.io/2018/06/05/metasyntactic-variables-foo-bar/

문득 생각났는데 이런 비하인드가 있다고 합니다.

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

아하 저도 맨날 foo, bar 이름을 보면서 '왜 이런 이름을 사용하지?' 라는 궁금증이 있었는데 답은 '우리도 몰라' 였군요! 😄

Copy link
Collaborator

@whddltjdwhd whddltjdwhd left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

정리하시느라 고생하셨어요~ 쉬어가는 느낌이어서 좋았습니다ㅎㅎ 👍 👍

Comment on lines +57 to +62
전역 네임스페이스 객체를 생성하고 해당 객체에 사용하고 싶은 변수를 프로퍼티로 추가하는 방법이다.
```javascript
var MYAPP = {};

MYAPP.name = 'Lee';
```
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

https://www.nextree.co.kr/p7650/
namespace 패턴에 대해서 좀 더 조사해보았는데

  1. 모든 변수와 함수에 상위객체 명을 붙여야하므로 소스코드 증가
  2. 전역 객체의 크기가 증가하면 할수록 접근 및 수정 비용이 증가

위와 같은 단점들도 존재해서 이 점도 잘 고려해서 쓰면 좋을 것 같아요! 😃

console.log(person.name); // 'Kim'
```
# 15.4 var vs. let vs. const
`var`를 쓰지 말고 `let`과`const`를 애용하도록 하자. 지역 스코프 관리, 재할당 문제 등에서 ES6에서부터 도입된 `let`, `const`를 사용하는게 좋다.
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Let's use 'const'! 👍

Copy link
Collaborator

@joeuns joeuns left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

정리 수고하셨씁니다~!! 👍


console.log(x); // 10
```
`var`로 할당된 변수는 함수 스코프만을 지역 스코프로 인정한다. 따라서 전역 스코프에 `x`를 선언하고 조건문 내부에서 `var` 키워드를 이용해 새로 변수 할당을 했다고 해도 전역 변수 `x`의 값이 변경된다.
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

의도치않게 변경될 수 있어서 let과 const가 도입되기 전에는 IIFE(즉시 실행 함수 표현식)를 써서 스코프를 인위적으로 분리하는 패턴이 많이 사용됐다고 하네요 ..!

const TAX_RATE = 0.1;
```
## 15.3.4 const 키워드와 객체
원시값과 다르게 `const` 키워드로 선언한 변수에 객체를 할당하면 객체 내부의 값을 변경할 수 있다.
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

객체를 완전히 불변으로 만들고 싶다면 Object.freeze 를 사용하는 방법이 있다고 합니당,

const obj = Object.freeze({ name: 'Lee' });
obj.name = 'Kim'; // 무시됨, 오류는 아님
console.log(obj.name); // 'Lee'

Copy link
Member

@clicelee clicelee left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM🥳

@junepil junepil merged commit 1e19d82 into main Nov 16, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

7 participants