Javascript 헷갈렸던 내용, 새로 알게된 내용 정리
→ Object

Object

Object 생성 & Property 삭제

/* create object */
const obj1 = {}; // 'object literal' syntax
const obj2 = new Object(); // 'object contructor' syntax


/* delete obj property */
obj1.target = 'value';
delete obj1.target;


Function을 이용해 Object를 생성

function makePerson(name, location){
  return {
    name : name,
    location : location
  };
}

const person = makePerson('jay','seoul');

이 때, object의 key와 value가 같을 각각 모두 표기하지 않고 한번만 표기 가능. (ES6문법 property shorthand)

function makePerson(name, location){
  return {
    name,
    location
  };
}

const person = makePerson('jay','seoul');


Constructor Function을 이용해 Object 생성

function Person(name, location){
  this.name = name;
  this.age = location;
}

const person = makePerson('jay','seoul');

일반 Function에서 몇가지 변화가 있다.

  • 함수 이름이 대문자로 시작
  • return {key: value} 형식에서 this.key = value 형식으로 작성

이렇게 선언된 Function을 Contructor Function 이라고 한다.

in operator (key 존재 여부 확인)

console.log('name' in person); // true
console.log('location' in person); // true
console.log('age' in person); // false

for..in vs for..of

for (key in obj)

for (key in person) {
  console.log(key);
}

/* 출력결과 */
// name
// location

for..in 반복문을 통해 person 인스턴스가 가지고 있는 key에 접근하는 방법.


for (value of iterable)

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

/* 출력결과 */
// 1
// 2
// 4

for..of 반복문을 통해 배열이 가지고있는 값에 접근하는 방법.


Object 복사

  • 얕은복사
const user = {name: 'jay', location: 'seoul'};
const user2 = user;

이 경우에는 결과적으로 user2를 수정하면 user의 값도 변경된다.

  1. 메모리에 user변수의 실제 값 위치를 가리키는 ‘reference’가 들어있고,
  2. user2도 동일한 user와 동일한 ‘reference’가 설정된 상태에서
  3. 어느 한쪽에서 값 변경을 통해 실제 값이 바뀌면
  4. 동일한 위치정보(reference)를 가지고있는 user와 user2모두 바뀌기 때문
  • 깊은복사 (별개의 오브젝트가 되도록 복사하는 방법)
/* old way */
const user3 = {};
for (key in user) {
  user3[key] = user[key];
}

/* new way 1 */
const user4 = {};
Object.assign(user4, user);

/* new way 2 */
const user4 = Object.assign({}, user);
  • another example
const fruit1 = {color : 'red'};
const fruit2 = {color : 'blue', size : 'big'};
const fruit3 = {color : 'yellow', price : 5000};

const mixed = Object.assign({}, fruit1, fruit2, fruit3);
console.log(mixed.color);
console.log(mixed.size);
console.log(mixed.price);

/* 출력결과 */
// yellow
// big
// 5000

Leave a comment