자바스크립트 5: Objects

수정·2022년 6월 12일
0

1

목록 보기
9/12
post-thumbnail

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 sue = { name: 'sue', age: '8'};
print(sue);

// with JavaScript magic (dynamically typed language)
// can add properties later
sue.hasJob = true;
console.log(sue.hasJob);
=true

//can delete properties later
delete sue.hasJob;

2. Computed(계산된) properties
: key should be always string

console.log(sue.name);
// .: 코딩하는 순간 .이라는 값을 받아오고 싶을 때 사용
console.log(sue['name']);
// ['']: 정확히 어떤 키가 필요한지 모를 때
sue['hasJob'] = ture; 
// 이렇게 변경도 가능하다.

3. Property value shorthand

const person1 = {name: 'bob', age: 2};
const person2 = {name: 'aha', age: 3};
const person3 = {name: 'hoho', age: 4};
const person4 = new Person('elile', 30);
concole.log(person4)

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 sue);
=true
console.log('random' in sue);
=false
console.log(sue.random)
=undefined

6. for..in vs for..of

// for (key in obj)
for (key in sue) {
    console.log(key);
}

// for (value of iterable)
const array = [1, 2, 4, 5];
for (value of array) {
    console.log(value);
}

7. Fun cloning

  • object.assign(dest, [obj1, obj2, obj3,,,])
const user = { name: 'sue', age: '20' };
const user2 = user;
console.log(user);
=name: "sue", age: "20"

//old way
const user3 ={};
for (key in user) {
    user3[key] = user[key];
}

//cloning
const user4 = object.assign({}, user);
console.log(user4);
=name: "sue", age: "20"

출처: 드림코딩 자바스크립트 기초 강의 (ES5+)

0개의 댓글