오브젝트는 어렵다. (ft. JavaScript ES6)

너겟·2022년 5월 27일
0

Learning_Javascript

목록 보기
5/5
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 };

'use strict';

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);

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

// can delete properties later
delete ellie.hasJob;
console.log(ellie.hasJob);

2. Computed properties

// key should be always string
[]안에는 꼭 string이 들어가야 한다. 얘는 언제쓰냐면 runtime에서 변수가 결정되는 경우, key로 뭐가 들어올지 모르는 경우 쓴다.

console.log(ellie.name);
console.log(ellie['name']);
ellie['hasJob'] = true;
console.log(ellie.hasJob);

function printValue(obj, key) {
  console.log(obj[key]);
}
printValue(ellie, 'name');
printValue(ellie, 'age');

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);

// 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)

key가 있는지 확인할 수 있다.
for문으로 돌리면서 모두 한번에 찾을 수도 있음

console.log('name' in ellie);
console.log('age' in ellie);
console.log('random' in ellie);
console.log(ellie.random);

6. for..in vs for..of

// for (key in obj)

console.clear();
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. Fun cloning

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

const user = { name: 'ellie', age: '20' };
const user2 = user;
console.log(user);

// old way
const user3 = {};
for (let key in user) {
  user3[key] = user[key];
}
console.clear();
console.log(user3);

const user4 = Object.assign({}, user);
console.log(user4);

// another example
const fruit1 = { color: 'red' };
const fruit2 = { color: 'blue', size: 'big' };
const mixed = Object.assign({}, fruit1, fruit2);
console.log(mixed.color);
console.log(mixed.size);
profile
꾸준하게 하는 법을 배우는 중입니다!

0개의 댓글