2. 알아 두어야 할 자바스크립트

진영민·2022년 9월 3일
0

Node.js 교과서

목록 보기
2/13

해당 내용은 Node.js 교과서 2판의 내용을 요약, 정리한 것입니다.

ES2015+

ES2015이상의 자바스크립트를 통틀어 ES2015+라고 하자.

const, let

var은 함수 스코프, 블록에 관계 없이 접근할 수 있음.
const, let은 블록 스코프, 블록 밖에서는 변수에 접근할 수 없음.
const는 재할당이 불가능

템플릿 문자열

큰 따옴표나 작은 따옴표와는 다르게 `으로 감싼다.
문자열 안에 변수를 넣을 수 있다.

const num3 = 1;
const num2 = 2;
const result = 3;
const string2 = `${num3} 더하기${num2}는 '${result}'`;
//1 더하기 2는 '3'

객체 리터럴

이전 문법으로 객체에 동적으로 속성을 추가하는 방법

var sayNode = function(){
	console.log('Node');
};
var es='ES';
var oldObject = {
	sayJS: function(){
    	console.log('JS');
    },
    sayNode: sayNode,
};
oldObject[es + 6] = 'Fantastic';
oldObject.sayNode();
oldObject.sayJS();
console.log(oldObject.ES6);

이러한 코드를 다르게 쓰면

var sayNode = function(){
	console.log('Node');
};
var es='ES';
const newObject = {
	sayJS() {
    	console.log('JS');
    },
    sayNode,
    [es + 6]: 'Fantastic',
};
newObject.sayNode();
newObject.sayJS();
console.log(newObject.ES6);

sayJS같은 객체의 메서드에 함수를 연결할 때 더는 콜론과 function을 붙이지 않아도 된다.
속성명과 변수명이 동일한 경우에는 한 번만 써도 되게 바뀌었다.

array function

function add1(x,y){
	return x + y;
}

const add2 = (x,y)=>{
	return x + y;
};

const add3 = (x,y)=>x + y;

const add4 = (x,y)=>(x + y);

위의 함수들은 동일한 역할을 한다. return문을 줄일 수 있으므로 자주 사용한다.

다른 점은 this의 바인드 방식이다.

var relationship1 = {
	name: 'zero',
    friends: ['nero', 'hero', 'xero'],
    logFriends:function(){
    	var that = this;
        this.friends.forEach(function (friend){
        	console.log(that.name, friend);
        });
    },
};
relationship1.logFriends();

const relationship2 = {
	name: 'zero',
    friends: ['nero', 'hero', 'xero'],
    logFriends(){
    	this.friends.forEach(friend=>{
        	console.log(this.name, friend);
        });
    },
};
relationship2.logFriends();

function에서는 relationship1을 var로 정의하여 간접적으로 접근했지만,
화살표 함수는 상위 함수의 스코프를 그대로 물려받는다.

구조분해 할당

객체와 배열로부터 속성이나 요소를 쉽게 꺼낼 수 있다.

var candyMachine = {
	status: {
    	name: 'node',
        count: 5,
    },
    getCandy: function(){
    	this.status.count--;
        return this.status.count;
    },
};
var getCandy = candyMachine.getCandy;
var count = candyMachine.status.count;

const candyMachine = {
	status: {
    	name: 'node',
        count: 5,
    },
    getCandy(){
    	this.status.count--;
        return this.status.count;
    },
};
const{ getCandy, status: { count } } = candyMachine;

위 코드는 candyMachine객체 안에 속성을 찾아서 변수와 매칭한다.
하지만 구조분해 할당을 사용하면 this가 달라질 수 있어 bind함수를 따로 사용해 주어야 한다.

해당 문법도 가능하다.

const array = ['nodejs', {}, 10, true];
const [node, obj, , bool] = array;

클래스

클래스 기반으로 동작하는 것이 아니라 프로토 타입 기반으로 동작한다. 프로토타입 기반 문법을 보기 좋게 클래스로 바꾼 것이라고 이해할 수 있다.

class Human {
	constructor(type='human'){
    	this.type = type;
    }
    
    static isHuman(human){
    	return human instanceof Human;
	}
}

class Zero extends Human{
	constructor(type, firstName, lastName){
    	super(type);
        this.firstName = firstName;
        this.lastName = lastName;
    }
}

프로미스

자바스크립트와 노드의 API들이 콜백 대신 프로미스 기반으로 재구성되며, 악명 높은 콜백 지옥 현상을 극복했다는 평가를 받는다.

프로미스를 쉽게 설명하자면, 실행은 바로 하되 결과값은 나중에 받는 객체이다.

const condition = true;
const promise = new Promise((resolve, reject)=>{
	if(condition){
    	resolve('성공')ㅣ
    }else{
    	reject('실패');
    }
});

promise
	.then((message)=>{
    	console.log(message);
    })
    .catch((error)=>{
    	console.log(error);
    })
    .finally(()=>{
    	console.log('무조건');
    });

여러 개의 프로미스를 동시에 실행할 수 있는 방법이 있다.

const promise1 = Promise.resolve('성공1');
const promise2 = Promise.resolve('성공2');
Promise.all([promise1, promise2])
	.then((result)=>{
    	console.log(result);
    })
    .catch((error)=>{
    	console.error(error);
    });

프로미스가 여러개 있으면 모두 resolve 될 때 까지 기다렸다가 then으로 넘어간다.
promise중 하나라도 reject되면 catch로 넘어간다.

async/await

노드 7.6 버전부터 지원되는 기능이며, ES2017에 추가되었다.
프로미스를 사용한 문법을 깔끔하게 줄인다.
for문과 함께 쓰는 것은 노드 10 버전부터 지원하는 ES2018문법이며, 이를 이용하면 위의 프로미스 문법을 줄일 수 있다.

const promise1 = Promise.resolve('성공1');
const promise2 = Promise.resolve('성공2');
(async () =>{
	for await (promise of [promise1, promise2]){
    	console.log(promise);
    }
})();

프런트엔드 자바스크립트

AJAX

비동기적 웹 서비스를 개발할 때 사용하는 기법.
이름에 XML이 들어 있지만 꼭 XML을 사용해야 하는 것은 아니며, 요즘에는 JSON을 많이 사용함.

쉽게 말해 페이지 이동 없이 서버에 요청을 보내고 응답을 받는 기술이다.

AJAX요청은 jQuery나 axios같은 라이브러리를 이용해서 보낸다.

먼저 get 요청을 보내면,

axios.get('https://www.naver.com')
	.then((result)=>{
    	console.log(result);
        console.log(result.data);
    })
    .catch((error)=>{
    	console.error(error);
    });

이는 async/await방식으로 변경할 수 있다.

(async ()=>{
	try{
    	const result = await axios.get('https://www.naver.com');
        console.log(result);
        console.log(result.data);
    }catch (error){
    	console.error(error);
    }
})();

FormData

HTML form 태그의 데이터를 동적으로 제어할 수 있는 기능. 주로 AJAX와 함께 사용된다.

const formData = new FormData();
formData.append('name','zerocho');

이러한 문법으로 키-값 형식으로 데이터를 저장할 수 있다.

encodeURIComponent, decodeURIComponent

주소에 한글이 들어가는 경우 서버가 한글 주소를 이해하지 못하는 경우가 있다.
이럴 때는 window객체의 메서드인 encodeURIComponent를 사용한다.
${encodeURIComponent('노드')}로 사용할 수 있으며, 변환된 문자열은
decodeURIComponent('변환된 문자열')을 통해서 복구할 수 있다.

profile
코린이

0개의 댓글