패스트캠퍼스 강의를 정리한 내용입니다.
"The RED : 프론트엔드 Back to the Basics : 지속 가능한 코드작성과 성능 향상법 by 김태곤"
<script>
태그도 ESM을 지원함<script>
태그에서 type을 모듈로만 써두면 모듈 방식을 사용해서 스크립트 파일을 불러올 수 있음한 때 잠깐 사용되었던 AMD 방식은 이제는 번들러의 영향으로 널리 사용되지 않지만, NodeJS의 기본 모듈 로딩 방식인 CommonJS와 ESM 방식은 아직도 널리 사용되고 있다.
Lexical Environment
Execution Context
*실행 컨텍스트는 함수를 실행하면서 발생하고 함수 실행이 종료되면 사라짐
Lexical Scope
<script>
// 아래 코드 실행 시 Uncaught Reference 에러 발생
function hello() {
{
const greeting = '안녕하세요';
}
console.log(greeting);
}
hello();
</script>
Closure
<script>
function hello() {
const greeting = '안녕하세요';
// 함수 객체를 반환
return function() {
console.log(greeting);
};
}
// hello() 함수를 실행하면 hello() Execution Context가 만들어짐
// 전역 실행 컨텍스트에 반환된 함수 객체 저장
const say = hello();
say();
</script>
참고: https://beomy.tistory.com/13
*Babel이나 번들러없이 Vanilla 자바스크립트를 사용시에는 직접 추가해서 엄격한 모드를 기본으로 사용하는 것을 추천
<script>
"use strict"
// 1.선언하지 않은 변수에 값을 할당할 수 없음
str = "hello, world";
// 2.읽기 전용 전역 객체에 값을 할당하면 에러 발생
// (일반 모드에서는 조용한 에러로 처리됨)
var undefined = 5;
var Infinity = 5;
NaN = "Wow";
// 3.지울 수 없는 값을 지우려고 하면 에러가 발생
// (일반 모드에서는 조용한 에러로 처리됨)
delete Object.prototype;
// 4.함수 파라미터에 중복 이름을 사용할 수 없음
function sum(a, a, c) {
console.log(a + a + c);
}
sum(1, 2, 3);
// 5. ES5의 8진수 리터럴 사용 불가 (애초에 표준도 아니었음)
const hex = 0xff; // 16진수
const octal = 020; ❌
const octal = 0o20; ⭕ // ES2015의 8진수 표현 방식
console.log(octal);
</script>
<script>
// 일치 연산자를 사용하지 않은 경우
1 == 1 // → true
1 == '1' // → true
1 == 2 // → false
'' == false // → true
[] == false // → true, []는 falsy 값도 아님
null == undefined // → true
// 일치 연산자를 사용한 경우
1 === 1 // → true
1 === '1' // → false
1 === 2 // → false
'' === false // → false
[] === false // → false
null === undefined // → false
</script>
Asynchronous JavaScript
<script>
// 콜백 지옥 예제
fs.readdir(source, function(err, files){
if(err) {
console.log('Error finding files: ' + err)
} else {
files.forEach(function (filename, fileIndex) {
console.log(filename)
gm(source + filename).size(function (err, values) {
if(err) {
console.log('Error identifying file size: ' + err)
} else {
console.log(filename + ' : ' + values)
aspect = (values.width / values.height)
widths.forEach(function (width, widthIndex) {
height = Math.round(width / aspect)
console.log('resizing ' + filename + 'to ' + height + 'x' + height)
this.resize(width, height).write(dest + 'w' + width) + '_' + filename, function(err) {
if(err) console.log('Error writing file: ' + err)
})
}.bind(this))
}
})
})
}
})
</script>
❗ 위의 예제 코드 개선 TIP
<script>
// 위의 콜백 지옥 예제를 개선한 코드
function writeImageTo(aspect, widthIndex, width) {
height = Math.round(width / aspect)
console.log('resizing ' + filename + 'to ' + height + 'x' + height)
this.resize(width, height).write(dest + 'w' + width) + '_' + filename, function(err) {
if(err) console.log('Error writing file: ' + err)
})
}
function resizeSingleImage(filename) {
console.log(filename)
gm(source + filename).size(function (err, values) {
if(err) {
console.log('Error identifying file size: ' + err)
return;
}
console.log(filename + ' : ' + values)
aspect = (values.width / values.height)
widths.forEach(writeImageTo.bind(this, aspect, widthIndex));
})
}
fs.readdir(source, function(err, files){
if(err) {
console.log('Error finding files: ' + err)
return;
}
files.forEach(resizeSingleImage);
})
</script>
1. Promise: 비동기 처리를 위한 객체
mdn Promise 명세: https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/Promise
2. async/await: 보다 편리한 비동기 처리
<script>
async function getName() {
return '김태곤';
}
// 위의 코드는 아래와 같음
function getName() {
return Promise.resolve('김태곤');
}
</script>
비동기 처리 예제: https://codesandbox.io/s/fancy-river-ltjcu?file=/src/index.js