본문 바로가기
Front-end/Web

[JS] 오브젝트

by 안녕주 2021. 8. 27.

Objetct

[Literals and properties]

- object를 만드는 법 (1) object literal을 사용해서 생성 (2) object constructor을 이용해서  생성

- object는 추후에 property를 추가/삭제할 수 있다.

- object는 key와 value의 집합체다.

'use strict';
// 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);

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

 

[Computed properties]

- 일반적인 . 방법을 사용할 때 : 코딩하는 그 순간 그 키의 값을 받아오고 싶을 때 사용

- computed properties방법 []을 사용할때 : 우리가 정확한 어떤 키가 필요한지 모를 때, 런타임에서 결정할때, 실시간으로 알고 싶을 때 사용

- key는 항상 string 타입이여야한다.

// 2. Computed properties
// key should be always string
console.log(ellie.name);
console.log(ellie['name']);
ellie['hasJob'] = true;
console.log(ellie.hasJob);

function printValue(obj, key) {
  console.log(obj[key]); //obj.key 불가 --> obj에 key라는 propertie가 있니..? X
}
printValue(ellie, 'name');
printValue(ellie, 'age');

 

[Property value shorthand] [Constructor Function]

- 순수하게 object를 생성하는 함수는 첫글자를 대문자로 시작하도록 한다. 

- return을 사용하지 않고 this를 사용해 작성

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

// 4. Constructor Function
function Person(name, age) {
  // this = {};
  this.name = name;
  this.age = age;
  // return this;
}

 

[in opertator : property existence check (key in obj)]

- in이라는 키워드를 통해 해당 key가 object안에 있는지 확인한다.

// 5. in operator: property existence check (key in obj)
console.log('name' in ellie);
console.log('age' in ellie);
console.log('random' in ellie);
console.log(ellie.random);

 

[for..in vs for..of]

- for..in : obj의 key들을 하나하나씩 가져와 반복

- for..of :  배열, 리스트와 같은 literable한 값을 하나하나 가져와 반복

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

 

[Fun cloning]

// 7. Fun cloning
// Object.assign(dest, [obj1, obj2, obj3...])
const user = { name: 'ellie', age: '20' };
const user2 = user; // 둘이 같은 것을 참조하고 있다.
user2.name = 'coder'
console.log(user); //name이 coder로 변경되어 있다.

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

//another example
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); //blue
console.log(mixed.size); //big

 

 

 

참고 사이트

https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/Object

 

Object - JavaScript | MDN

Object 생성자는 객체 래퍼(wrapper)를 생성합니다.

developer.mozilla.org


Thanks for 드림코딩

https://youtu.be/1Lbr29tzAA8

댓글