자바스크립트 복습 - 3

Stulta Amiko·2022년 5월 6일
0

자바스크립트 복습

목록 보기
3/12
post-thumbnail

화살표 함수(Arrow function expression)

const plane = function(maker, color) {
    return "maker: " + maker + " color: " + color;
}

console.log(plane("airbus", "red")); //maker: airbus color: red

기존의 함수를 사용하는 방법

기존의 함수를 선언할때는 function()을 사용해서 선언했다.

const plane = (maker, color) => {
    return "maker: " + maker + " color: " + color;
}

console.log(plane("airbus", "red")); //maker: airbus color: red

ES6에서 새롭게 생긴 화살표 함수의 사용형태

새롭게 등장한 화살표함수(2015)는 다음과 같이 사용한다 () => {}
파라미터가 한개만 있을때는 괄호를 생략해도되고
파라미터가 없을때에는 빈괄호를 이용한다.

암시적 반환

const plane = (color) => "color: " + color;

console.log(plane("red")); // color: red

화살표함수를 사용하면 명시적인 반환을 생략하고 반환할 수 있다.

객체를 반환해야 한다면 map함수를 이용해서 객체를 반복 할 수 있다.

const plane = "plane company";
const company = ["Boeing", "Airbus", "Bombardier"];

const result = company.map((maker, i) => ({ company: maker, order: i }));
console.log(result); 
/*[
  { company: 'Boeing', order: 0 },
  { company: 'Airbus', order: 1 },
  { company: 'Bombardier', order: 2 }
]*/

.map()을 이용해서 배열의 반복을 하는 모습

.map()의 첫번째 파라미터로는 현재원소를 두번째 파라미터로는 배열의 인덱스를 넣어준다.

화살표 함수의 this

화살표 함수 내부에서는 this 키워드를 사용할때 일반 함수와 다르게 동작한다.
화살표 함수를 사용할 때 this 키워드는 상위 스코프에 상속된다.

const plane = {
    maker: "boeing",
    type: 737,
    change: function() {
        this.type++;
        console.log(this.type);
    },
};

plane.change(); // 738

const plane2 = {
    maker: "boeing",
    type: 737,
    change: () => {
        this.type++;
        console.log(this.type); //nan
    },
};

plane2.change();

화살표 함수에서 this는 window 객체를 가르킨다.

가르키는데..
문제는 증감연산자는 nan이 뜨는데 그냥 값을 바꾸면 정상작동된다.
책이 잘못된건지 뭐가 어떻게 된건지 모르겠다.
어쨋거나 화살표 함수에서 this는 상위 스코프에 상속된다는 점을 기억하자.

function example() {
    console.log(arguments[0]);
}

example(1, 2, 3); // 1

argument 객체는 함수 내부에서 접근할 수 있는 배열 객체이고 함수에 전달된 아규먼트의 값을 담고있다.

argument[0]을 이용하면 첫번째 아규먼트에 접근할 수 있다.

const show = () => {
    const first = arguments[0];
    console.log(first);
}

show("Boeing", "airbus", "bombardier"); // {}

이 코드는 빈 배열을 반환한다.

화살표 함수에서 위 코드와 같은 코드를 정상적으로 사용하려면

const show = (...args) => {
    const first = args[0];
    console.log(first);
}

show("Boeing", "airbus", "bombardier");  //Boeing

다음과 같은 코드를 이용한다. ...은 스프레드 문법이다.

함수 파라미터의 기본값

function func(arg1, arg2, arg3) {
    if (typeof arg2 === 'undefined') {
        arg2 = 'itay';
    }
    if (typeof arg3 === 'undefined') {
        arg3 = 'ta';
    }
    console.log(arg1, arg2, arg3);
}

func('k'); // k itay ta

arg2와 arg3의 기본값을 설정하고 arg1만 따로 설정하는 코드

만약 arg1을 맨뒤로 밀고 arg2와 arg3의 값은 빈채로 코드에 넣고싶지만 직접 undefined를 넣지 않는이상 불가능하다.

function calc(total,tax=0.1,tip=0.05){
    return total+(total*tax)+(total*tip);
}

calc(1000,0.15) //tip에 0.15를 적용하려 하지만 tax에 적용된다. 
calc(1000,undefined,0.15) //tip에 적용되지만 깔끔한 방법은 아니다. 

ES6 에서는 이런식으로 파라미터의 기본값을 설정할 수 있지만 위 방법은 깔끔하지는 않다.

함수의 파라미터를 객체로 만들면 주어진 키에 맞춰서 입력되기 떄문에 순서에 구애받지 않아도 된다.

function calc({ total = 0, tax = 0.1, tip = 0.05, } = {}) {
    return total + (total * tax) + (total * tip);
}

console.log(calc({ total: 100, tip: 0.5 })); //160

이런식으로 객체를 입력받으면 된다.

만약 calc함수에서 빈배열을 추가하지 않는다면 프로퍼티를 읽지 못하는 오류가 발생한다.

템플릿 리터럴

const maker = 'Boeing';
const introducing = 'this is ' + maker;

console.log(introducing); //this is Boeing

기존의 문자열을 삽입하기 위한 코드

기존에는 개행과 표현식 혹은 변수를 삽입하기가 불편한 형태였다.

const maker = 'Boeing';
const introducing = `this is ${maker}`;

console.log(introducing); //this is Boeing

ES6에서는 백틱을 사용하여 더 간단히 사용할 수 있다.

백틱을 이용해서 변수를 넣는 코드를 볼 수 있다.

중첩 템플릿

const obj = [{
    maker: "Airbus",
    color: "white",
}, {
    maker: "Boeing",
    color: "blue",
}, {
    maker: "Bombardier",
    color: "red",
}, ];

const html = `
<ul>
    ${obj.map((object,i) => `<li>${object.maker} and ${object.color}</li>`)}
</ul>
`
console.log(html);
//
<ul>
    <li>Airbus and white</li>,<li>Boeing and blue</li>,<li>Bombardier and red</li>
</ul>

이런식으로 중첩 템플릿을 이용할 수 도 있다.

템플릿 리터럴에 함수 전달하기

const plane = {
    boeing: "747",
    airbus: "330",
    bombardier: "cs300",
    others: ["cessna172", "MD-11", "Fokker100"],
}

function otherList(others) {
    return `
    <p>${others.map(plane => `<span>${plane}</span>` ).join('\n')}</p>
    `
}

const html = `
    <div>
        <p>${plane.boeing}</p>
        <p>${plane.airbus}</p>
        <p>${plane.bombardier}</p>
        <p>${otherList(plane.others)}</p>
    </div>
`;

console.log(html);

실행결과

<div>
    <p>747</p>
    <p>330</p>
    <p>cs300</p>
    <p>
<p><span>cessna172</span>
	<span>MD-11</span>
	<span>Fokker100</span></p>
	</p>
</div>

이런식으로 템플릿 리터럴내에 함수를 전달할 수 도있다.

태그된 템플릿 리터럴

함수를 태그하여 템플릿 리터럴을 실행하면 템플릿 내부에 있는 모든 항목이 태그된 함수의 인수로 제공된다.
- 모던 자바스크립트 핵심가이드

무슨말인지 잘 모르겠으니 책에 나온 예제를 한번 쳐보면서 이해를 하자

let person = "alber";
let age = 25;

let person = "alber";
let age = 25;

function myTag(strings, personName, personAge) {
    let str = strings[1];
    let ageStr;
    personAge > 50 ? ageStr = "grandpa" : ageStr = "youngman";
    return personName + str + ageStr;
}

let sentence = myTag `That ${person} is a ${age} !`;
console.log(sentence); //alber is a youngman

실행결과를 보면 변수를 제외한 That,is a,!가 strings가 된다.

0개의 댓글