26장 ES6 함수의 추가 기능

ES6에서의 함수의 추가 기능에 대해서 알아보자.

26.1 함수의 구분

// 프로퍼티 f에 바인딩된 함수는 callable이며 constructor다.
var obj = {
    x: 10,
    f: function () { return this.x; }
}
// 프로퍼티 f에 바인딩된 함수를 메서드로서 호출
console.log(obj.f()); // 10
// 프로퍼티 f에 바인딩된 함수를 일반 함수로서 호출
var bar = obj.f;
console.log(bar()); // undefined
// 프로퍼티 f에 바인딩된 함수를 생성자 함수로서 호출
console.log(new obj.f()); // f {}

26.2 메서드

const derived = {
    __proto__: base,
    // sayHi는 ES6 메서드가 아니다.
    // 따라서 sayHi는 [[HomeObject]]를 갖지 않0므루 super 키워드를 사용할 수 없다.
    sayHi: function () {
        // SyntaxError: 'super' keyword unexpected here
        return ${super .sayHi()} . : How are you doing?' ;
    }
};

26.3 화살표 함수

26.3.1 화살표 함수 정의
// concise body
const power = x => x ** 2;
power(2); // — 4
// 위 표현은 다음과 동일하다.
// block body
const power = x => { return x ** 2; };
const create = (id, content) => ({ id, content });
create(l, ' JavaScript'); // {id: 1, content: "JavaScript"}
// 위 표현은 다음과 동일하다.
const create = (id, content) => { return { id, content }; };
26.3.2 화살표 함수와 일반 함수의 차이
  1. 화살표 함수는 인스턴스를 생성할 수 없는 non-constructor다.
  2. 중복된 매개변수 이름을 선언할 수 없다.
  3. 화살표 함수는 함수 자체의 this, arguments, super, new. target 바인딩을 갖지 않는다.
    • 따라서 화살표 함수 내부에서 this, arguments, super, new.target을 참조하면 스코프 체인의 상위 스코프의 this, arguments, super, new.target을 참조한다.
26.3.3 this
class Prefixer {
    constructor(prefix) {
        this.prefix = prefix;
    }
    add(arr) {
        // add 메서드는 인수로 전달된 배열 arr을 순회하며 배열의 모든 요소에 prefix를 추가한다.
        // 1
        return arr.map(function (item) {
        return this.prefix + item; // 2
        // TypeError: Cannot read property 'prefix' of undefined
        });
    }
}
const prefixer = new Prefixer('-webkit-1');
console.log(prefixer.add([' transition', 'user-select']));
class Prefixer {
    constructor(prefix) {
     this.prefix = prefix;
    }
    add(arr) {
        return arr.map(item => this.prefix + item);
    }
}
const prefixer = new Prefixer('-webkit-');
console.log(prefixer.add(['transition', 'user-select']))
// ['-webkit-transition’, '-webkit-user-select']

// increase 프로퍼티에 할당한 화살표 함수의 상위 스코프는 전역이다.
// 따라서 increase 프로퍼티에 할당한 화살표 함수의 this는 전역 객체를 가리킨다.
const counter = {
    num: 1,
    increase: () => ++this.num
}
console.log(counter.increase()); // NaN
// Bad
const person = {
    name: 'Lee',
    sayHi: () => console.log('Hi ${this.name}')
};
// sayHi 프로퍼티에 할당된 화살표 함수 내부의 this는 상위 스코프인 전역의 this가 가리카는
// 전역 객체를 가리키므로 이 예제를 브라우저에서 실행하면 this.name은 빈 문자열을 갖는 window.name과 같다.
// 전역 객체 window에는 빌트인 프로퍼티 nameOl 존재한다
// Bad
class Person {
    // 클래스 필드 정의 제안
    name = 'Lee';
    sayHi = () => console.log('Hi ${this.name}');
    const person = new Person();
    person.sayHi(); // Hi Lee  
}
class Person {
    constructor() {
    this.name = 'Lee';
    // 클래스가 생성한 인스턴스(this)의 sayHi 프로퍼티에 화살표 함수를 할당한다.
    // 따라서 sayHi 프로퍼티는 인스턴스 프로퍼티다.
    this.sayHi = () => console.log( Hi ${this.name}');
    }
}

26.3.4 super
26.3.4 arguments
(function () {
    // 화살표 함수 foo의 arguments는 상위 스코프인 즉시 실행 함수의 arguments를 가리킨다.
    const foo = () => console.log(arguments); // [Arguments] { '0': 1, '1' : 2 }
    foo(3, 4);
}(1, 2));
// 화살표 함수 foo의 arguments는 상위 스코프인 전역의 arguments를 가리킨다.
// 하지만 전역에는 arguments 객체가 존재하지 않는다. arguments 객체는 함수 내부에서만 유효하다.
const foo = () => console.log(arguments);
foo(1, 2); // ReferenceError: arguments is not defined

26.4 Rest 파라미터

26.4.1 기본 문법
26.4.2 Rest 파라미터와 arguments 객체
function sum() {
    // 유사 배열 객체인 arguments 객체를 배열로 변환한다.
    var array = Array.prototype.slice.call(arguments);
    return array.reduce(function (pre, cur) {
        return pre + cur;
    }, 0)
}
console.log(sum( 1, 2, 3, 4, 5)); // 15

function sum( ... args) {
    // Rest 파라미터 args에는 배열 [1, 2, 3, 4, 5J가 할당된다.
    return args.reduce((pre, cur) => pre + cur, 0);
}
console.log(sum(l, 2, 3, 4, 5)); // 15

26.5 매개변수 기본값

function sum(x, y) {
    // 안수가 전달되지 않아 매개변수의 값이 undefined인 경우 기본값을 할당한다.
    x = x I! 0;
    y = y !! 0;
    return x + y;
}
console.log(sum(l, 2)); // 3
console.log(sum(l)) // 1

function sum(x = 0, y = 0) {
return x + y;
}
console.log(sum(l, 2)); // 3
console.log(sum(l)) // 1

끝!