JS 기초 강의(ES5+) - # Objects(7)

Objects

  • one of the JavaScript's data types.
  • a collection of related data and/or functionality.
  • Nearly all objects in JavaScript are instances of Object
  • object = { key : value };

1. Literals and properties

  • const obj1 = {}; // 'object literal' syntax
    const obj2 = new Object(); // 'object constructor' syntax
    
    function print(person) {
      console.log(person.name);
      console.log(person.age);
    }
    
    const ellie = { name: 'ellie', age: 4 };
    print(ellie); // -> [ellie]
                 // -> [4]
  • (dynamically typed language), can add properties later

    ellie.hasJob = true; // 이렇게 동적으로 추가 가능 but 유지보수 힘듦.
    console.log(ellie.hasJob); // -> [ture]
    • can delete properties later
    delete ellie.hasJob;
    console.log(ellie.hasJob); // -> [undefined]

2. Computed properties

  • 키는 무조건 스트링 타입으로 (key should be always string)

    console.log(ellie.name); // -> [ellie]
    console.log(ellie['name']); // -> [ellie]
    ellie['hasJob'] = true;
    console.log(ellie.hasJob); // -> [true]
    
    function printValue(obj, key) {
      console.log(obj[key]);
    }
    printValue(ellie, 'name'); // -> [ellie] 
    printValue(ellie, 'age'); // -> [4]

3. Property value shorthand (키와 밸류의 이름이 동일하면 생략 가능)

  • const person1 = { name: 'bob', age: 2 };
    const person2 = { name: 'steve', age: 3 };
    const person3 = { name: 'dave', age: 4 };
    const person4 = new Person('elile', 30);
    console.log(person4); // -> [Person {name: "elile", age: 30}]

4. Constructor Function

  • function Person(name, age) {
      // this = {}; (생략)
      this.name = name;
      this.age = age;
      // return this; (생략)
    }

5. in operator: property existence check (key in obj)

  • console.log('name' in ellie); // -> true
    console.log('age' in ellie); // -> true
    console.log('random' in ellie); // -> false
    console.log(ellie.random); // -> undefined

6. for..in vs for..of

  • for (key in obj)
    for (let key in ellie) {
      console.log(key);
    }
  • for (value of iterable)
    const array = [1, 2, 4, 5];
    for (let value of array) {
      console.log(value);
    }

7. cloning

  • Object.assign(dest, [obj1, obj2, obj3...])

    const user = { name: 'ellie', age: '20' };
    const user2 = user;
    console.log(user); // -> [{name: "ellie", age: "20"}]
  • 예전 방법

    const user3 = {};
    for (let key in user) {
      user3[key] = user[key];
    }
    console.log(user3); // -> [{name: "ellie", age: "20"}]
  • 요즘 방법

    const user4 = Object.assign({}, user);
    console.log(user4); // -> [{name: "ellie", age: "20"}]
  • another example

    const fruit1 = { color: 'red' };
    const fruit2 = { color: 'blue', size: 'big' };
    const mixed = Object.assign({}, fruit1, fruit2); // 뒤에 있는 요소가 앞에 덮어씌움
    console.log(mixed.color); // -> [blue]
    console.log(mixed.size); // -> [big]

좋은 웹페이지 즐겨찾기