JS 함수

  • ES6에서 화살표 함수(Arrow Function) 도입 : =>
  • 비교 연산자 : <=, >=

기존 함수

  • 일반함수: 직접 함수를 호출한다.

    1
    2
    3
    4
    function add1(a, b) {
    return a + b;
    }
    console.log(add1(7, 8)); // 15
  • 익명함수: 간접함수 호출한다.

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    var add1_1 = function(x, y) {
    return x % y; // 30 % 14
    }
    console.log(add1_1(30, 14, 25)); // 2
    console.log(add1_1); // 함수구문
    // function(x, y) {
    // return x % y; // 30 % 14
    // }

    var add1_1 = 50;
    console.log(add1_1); // 50
  • const 변수 선언: 함수문은 고정이어야 한다.

1
2
3
4
const add2 = function(c, d) {
return c + d;
}
console.log(add2(10, 20)); // 30

화살표 함수 적용

  • function 제거
  • {} 대신 =>
  • return문만 존재할 때 return문을 제거할 수 있음
1
2
const add3 = (e, f) => e + f;
console.log(add3(14, 7)); // 21

매개변수가 하나만 존재할 때 방법1

1
2
const add4 = (g) => g + 9;
console.log(add4(6, 32)); // 15

매개변수가 하나만 존재할 때 방법2

  • 매개변수가 복수가 아닌 경우, 매개변수를 감싸고 있는 소괄호()를 생략 가능하다.
1
2
const add5 = h => h + 9;
console.log(add5(4, 6)); // 13
  • 함수 구문이 복잡한 경우 중활호 {}를 생략하면 안된다. (return문만 존재하는 경우가 아니라면)
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    const calc1 = (a, b, c) => {
    console.log(a);
    console.log(b);
    console.log(c);

    let sum = (a + b) * c;
    return `최종 결과값 : ${sum}`;
    }

    console.log(calc1(12, 14, 2)); // 최종 결과값 : 52

호이스팅

  • 함수 호출의 위치에 의해서 함수를 호출할 수 있는가에 대한 구성 방법

  • 함수구문(function() ~~)과 함수 호출문 위치에 의한 조정

  • 호이스팅의 의미 : “소형 감아올리는 장치(Lifting)” -> 함수구문이 아직 문서상에서 로딩되지 않았음에도 불구하고 함수 호출문이 함수구문보다 먼저 로딩되는 구조라고 하더라도 함수문이 실행

    1
    2
    3
    4
    5
    fnc1(); // 함수 구문을 호출
    // 호이스팅이 적용된 상태
    function fnc1() {
    console.log("fnc1의 호출에 의한 함수구문 실행");
    }
  • 익명함수에는 호이스팅을 막는 역할 (저장은 문서상에서 순서대로 적용되기 때문)

    1
    2
    3
    4
    fnc2(); // 오류 발생
    var fnc2 = function() {
    console.log("fnc2의 호출에 의한 함수구문 실행");
    }
    1
    2
    3
    4
    fnc3(); // Cannot access 'fnc3' before initialization
    const fnc3 = () => {
    console.log("fnc3의 호출에 의한 함수구문 실행");
    }

실습문제

세 수의 합계를 계산하는 방식으로 함수를 구성하시오.

  • 함수 호출문을 통해서 1, 2, 3을 함수 구문에 전달.
  • 화살표 함수를 이용하여 “최종합계 : 6”을 콘솔창에 구성하시오.
  • 매개변수와 return문을 통해서 값을 가져온다.
  • 반드시 변수(const)로 선언할 것.
1
2
const add = (a, b, c) => a + b + c
console.log(`최종합계 : ${add(1, 2, 3)}`);

“스누피”라는 문구를 “카카오”로 변경

1
<h1 id="ch_txt">스누피</h1>
1
2
3
4
5
const changeText = a => {
// document.querySelector("#ch_txt").textContent = a;
document.querrySelector("#ch_txt").innerText = a;
}
changeText("카카오");

“스누피”라는 문구를 “스머프”로 변경

  • 함수 내부에서 리턴으로 받아서 콘솔창에 작성.
  • 콘솔창의 결과물 : 스머프 만세
    1
    <h1 id="ch_txt">스누피</h1>
    1
    2
    3
    4
    5
    const changeText = a => {
    document.querrySelector("#ch_txt").innerText = a;
    return `${a} 만세`;
    }
    console.log(changeText("스머프"));

this

1
2
3
4
<h3 id="arrowFunc_this">화살표 함수와 this 키워드</h3>
<div class="box open">
나는 박스 공간입니다.
</div>
1
2
3
4
5
6
7
8
9
10
11
12
13
.open {
width: 200px;
height: 200px;
border: 1px solid #aaf;
display: flex;
justify-content: center;
align-items: center;
cursor: pointer;
}

.opening {
background-color: #ffb;
}
1
2
3
4
5
const $box = doocument.querySelector(".box");
$box.addEventListener("clink", function() {
console.log(this); // <div class="box open">나는 박스 공간입니다.</div>
this.classList.add("opening");
});

화살표 함수

  • 화살표 함수가 부모 스코프 {}에서 this값을 상속한다는 것을 인지한다면, 에러가 발생하는 부분을 막기 위해서는 일반 함수로 작성되어야 한다.
    1
    2
    3
    4
    5
    const $box = doocument.querySelector(".box");
    $box.addEventListener("clink", () => {
    console.log(this); // Window {window...}
    this.classList.add("opening"); // Cannot read property...
    });
  • 객체에서도 메서드의 방법에 따라 점근되는 this 키워드 대상은 달라질 수 있음.
  • 객체에는 화살표 함수 안씀.
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    const person1 = {
    age : 10,
    grow : function() {
    console.log(this); // {age: 10, grow: f} ==> person1이라는 객체를 지칭함
    this.age++;
    console.log(this.age);
    }
    }
    console.log(person1.age); // 10
    person1.grow();
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    const person2 = {
    age : 10,
    grow : () => {
    console.log(this); // Window {window...}
    this.age++;
    console.log(this.age); // NaN
    }
    }
    console.log(person2.age); // 10
    person1.grow();
    1
    <h3>arguments 객체</h3>

일반 함수 내에서 arguments 객체 선언

1
2
3
4
5
function example0() {
console.log(arguments); // Arguments(3) [1, 2, 3, callee: f, Symbol(Symbol.iterator): f]
console.log(agruments[2]); // 3
}
example0(1, 2, 3);
1
2
3
4
5
const example1 = function() {
console.log(arguments); // Arguments(3) ['사과', '오렌지', '포도', callee: f, Symbol(Symbol.iterator): f]
console.log(agruments[1]); // 오렌지
}
example1("사과", "오렌지", "포도");

화살표 함수 내에서 arguments 객체 선언

1
2
3
4
const example2 = () => {
console.log(arguments); // arguments is not defined at example2
}
example2("삼성", "엘지", "현대");
1
2
3
4
5
6
const example3 = (...args) => {
const winner = args;
console.log(winner); // ['오리', '타조', '치타']
console.log(`${winner[2]}가 가장 빠르다.`);
}
example3("오리", "타조", "치타");

REFERENCE
뷰(Vue.js) 프로그래밍 과정 _ 하이미디어 아카데미

  • © 2020-2025 404 Not Found
  • Powered by Hexo Theme Ayer