러닝 자바스크립트 6장 정리

 

함수 

 - 하나의 단위로 실행되는 문의 집합이다. 

 

function sayHello() {

    console.log ("Hello world!");

    console.log ("Hola world!");

    console.log ("Hallo wereld!");

}

sayHello();

 - 함수 선언의 한 예

 

 

반환 값 

 - 함수 호출의 값 함수 안의 return 키워드를 사용하면 함수를 즉시 종료하고 값을 반환한다. 

 

function getGreeting() {

      return "Hello world!";

}

getGreeting();       // "Hello world!"

 - return을 명시적으로 호출하지 않으면 반환 값은 undefined가 된다. 

 

 

호출과 참조 

 

getGreeting();     // "Hello world!"

getGreeting;       // function getGreeting()

 - 괄호를 쓰지 않으면 다른 값과 마찬가지로 함수를 참조하는 것이 되며 함수는 실행되지 않음 

 

const f = getGreeting;

f();              // "Hello world!"

 

const o = {};

o.f = getGreeting;

o.f();          // "Hello world!"

 

const arr = [ 1, 2, 3 ];

arr[1] = getGreeting;

arr[1]();        // "Hello world!"

 - 함수는 변수, 객체 프로퍼티, 배열 등에도 할당할 수 있다. 

 

 

함수와 매개변수 

 

function avg (a,b) {

      return (a+b)/2;

}

avg (5, 10);     // 7.5

 - a와 b가 정해진 매개변수가 된다. 함수가 호출되면 정해진 매개변수는 값을 받아 실제 매개변수가 된다. 

함수 내부의 매개변수는 함수 바깥의 변수와는 전혀 다르다. (설사 이름이 같다고 하더라도)

 

 

매개변수 해체 

 

function getSentence ({ subject, verb, object }) {

    return '${subject} ${verb} ${object}';

}

const o = {

      subject : "I", 

      verb : "love",

      object : "JavaScipt",

};

getSentence(o);     // "I love JavaScript"

 - 프로퍼티 이름이 반드시 유효한 식별자여야 한다. 배열 역시 같은 방식으로 해체가 가능하다. 

 

 

 this 키워드 

 - 객체의 프로퍼티인 함수에서 메서드를 호출하면 this는 호출한 매서드를 소유하는 객체가 된다. 

 

const o = {

     name : 'Wallace',

     speak() { return 'My name is ${this.name}!' ;},

}

o.speak();       //"My name is Wallace!

 

 

call

 - call 메서드는 모든함수에서 사용가능하며 this를 특정 값으로 지정할 수 있다. call의 첫번째 매개변수는 this로 사용할 값이고, 매개변수가 더 있다면 그 매개변수는 호출하는 함수로 전달된다. 

 

const bruce = { name : "Bruce" };

const madeline = { name : "Madeline' };

 

function greet() {

    return 'Hello, Im ${this.name}!';

}

greet();                        // "Hello, Im undefined"

greet.call(bruce);            // "Hello, Im Bruce"

greet.call(madeline);      // "Hello, Im Madeline"

 

 

apply 

 - call은 매개변수를 직접 받지만, apply는 매개변수를 배열로 받는 것 외엔 완전 동일하다. 또한 배열 요소를 함수 매개변수로 사용해야 할 때 유용하다. 

 

update.apply (bruce, [1955, "actor"]);

                 // { name: "Bruce", birthyear" 1955 ~~~ }

update.apply (madeline, [1918, "writer"]);

                 // { name: "Madeline", birthyear" 1918 ~~~ }

 

 

bind

 - bind를 사용하면 this의 값을 영구히 바꿀 수 있다. 

 

const updateBruce = update.bind(bruce);

 

updateBruce (1904, "actor");

                  // { name: "Bruce", birthyear: 1904, occupation: "actor" }

updateBruce.call (madeline, 1274, "king")

                // { name: "Bruce", birthyear: 1274, occupation: "king" }

                // name은 변하지 않는다. 

 

 

화살표 표기법 

 - function이라는 단어와 중괄호 숫자를 줄이기 위해 고안된 단축 문법으로 세가지의 단축 문법이 있다.

 - function을 생략해도 된다. 

 - 함수에 매개변수가 하나뿐이라면 괄호 ( () )도 생략할 수 있다. 

 - 함수바디가 표현식 하나라면 중괄호와 return문도 생략할 수 있다. 

 - 화살표 함수는 항상 익명이다. 

 

const f1 = function() { return "hello!"; }

const f1 = () => "hello!";

 

const f2 = function(name) { return 'Hello, ${name}!'; }

const f2 = name => 'Hello, ${name}!';

 

const f3 = function(a, b) { return a + b; }

const f3 = (a, b) => a+b;

TAGS.

Comments