0%

Objects and DSs

Objects and Data Structures

  1. Getter and Setter

    • JS는 인터페이스 / 타입 / 접근제어자 (Access Modifier) 을 가지고 있지 않음

    • Object property를 가져오는 것 이상 (e.g., modify) 의 action을 하고 싶을 때, 일일이 접근제어자를 불러 action을 취하지 않아도 됨

    • set action 시 validation을 추가하는 것이 좋음

    • internal representation을 encapsulating

    • get, set시 logging이나 error handling을 추가하는 것이 용이함

    • get 시 lazy load 속성을 추가할 수 있음

    Lazy loading

    • It’s a way to shorten the length of the critical rendering path, which translates into reduced page load times
    • getting the properties from a server
    1. identify resources as non-blocking (non-critical)
    2. load these only when needed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
// bad
function makeBankAccount() {
// ...

return {
// ...
balance: 0
};
}

const account = makeBankAccount();
account.balance = 100;


// good
function makeBankAccount() {
// private으로 선언된 변수
let balance = 0;

// 아래 return을 통해 public으로 선언된 "getter"
function getBalance() {
return balance;
}

// 아래 return을 통해 public으로 선언된 "setter"
function setBalance(amount) {
// ... balance를 업데이트하기 전 검증로직
balance = amount;
}

return {
// ...
getBalance,
setBalance
};
}

const account = makeBankAccount();
account.setBalance(100);
  1. objects의 properties는 private로 만들기

    • closures
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    // bad
    const Employee = function(name) {
    this.name = name;
    };

    Employee.prototype.getName = function getName() {
    return this.name;
    };

    const employee = new Employee('John Doe');
    console.log(`Employee name: ${employee.getName()}`);
    // Employee name: John Doe
    delete employee.name;
    console.log(`Employee name: ${employee.getName()}`);
    // Employee name: undefined


    // good
    function makeEmployee(name) {
    return {
    getName() {
    return name;
    },
    };
    }

    const employee = makeEmployee('John Doe');
    console.log(`Employee name: ${employee.getName()}`);
    // Employee name: John Doe
    delete employee.name;
    console.log(`Employee name: ${employee.getName()}`);
    // Employee name: John Doe