본문 바로가기

Language & Framework/JavaScript

자바스크립트 기초. Object

Object? 

=> object(객체) = { key(property) : 값(value) }의 집합체

 

1. 객체 초기화 방법 ( literals와 propertys )

// 1) literal 객체 초기화
const object1 = {}; // literal

const babyddoddi = { name: "ddoddi", age: 7 };
console.log(babyddoddi); // {name: 'ddoddi', age: 7}

// 2) property 객체 초기화

function Adultddoddi(name, age) {
  this.name = name;
  this.age = age;
}
adultddoddi = new Adultddoddi("ddoddi", 29);
console.log(adultddoddi); // {name: ddoddi, age:29}

리터럴 객체 초기화는 아주 기본적인 객체 형태 그대로의 모습을 보여준다.

프로퍼티 객체 초기화는 클래스 선언과 비슷한 방법으로 가능하다.

 

adultddoddi.sex = "male";
console.log(adultddoddi); // {name: 'ddoddi', age: 29, sex: 'male'}

재미있는 사실은 JAVAScript는 동적 언어이기 때문에 추후에도 오브젝트에 key와 value를 추가할 수 있다.

 

 

2. computed properties ( 계산된 프로퍼티 )

프로퍼티(key)를 string으로 표현하게 해주는 것이다.

아래의 예제를 보면 알 수 있듯이 굉장히 간단하다.

let Ddoddi = {
  ["name"]: "ddoddi",
  ["age"]: 7,
};
console.log(Ddoddi); // { name: ddoddi,age: 7 }

 

약간 응용하면 이런 식으로도 사용할 수 있다

let c = 0;
const stackfactory = {
  ["stack" + c++]: c,
  ["stack" + c++]: c,
  ["stack" + c++]: c,
};
console.log(stackfactory); // {stack0: 1, stack1: 2, stack2: 3}

 

3. property value Shorthand (단축 속성명)

단축 속성명이 무엇이냐? 너무 간단하다.

객체의 property(key)와 value가 동일한 이름을 가지고 있을 시 { x: name, y: age, z:dream)이런 걸 안해도 된다는 의미이다.

const x = "samsung";
const y = "apple";
const z = "lg";

const smartphone = { x, y, z };
console.log(smartphone.z);

굿. 이를 활용해 바로 생성자 함수까지 알아보자!

 

4. Constructor function (생성자 함수)

객체를 생성하는 함수. 아주 정직한 이름과 정직한 기능이다.

간만에 이해하기 쉽고 간단한 친구들이 연속으로 나와서 기분이 좋다.

function Smartphone(manufacturer1, manufacturer2, manufacturer3) {
  return {
    manufacturer1, // 마찬가지로 생략이 가능하다
    manufacturer2, // 혹은 this.manufacturer2 = manufacturer2
    manufacturer3, // 아시죠? 호호
  };
}

const smartphone2 = new Smartphone("samsung", "apple", "lg");
console.log(smartphone2); // {manufacturer1: 'samsung', manufacturer2: 'apple', manufacturer3: 'lg'}
console.log(smartphone2.manufacturer1); // samsung

기분이 좋으니 이 코드를 가지고 in 연산자를 활용하는 것까지 가보자.

 

5. in operator (in 연산자)

in 연산자는 어떤 객체 안에 존재하는 메소드나 프로퍼티를 확인하는 것에 사용한다.

console.log("samsung" in smartphone2); // false
console.log("apple" in smartphone2); // false
console.log("lg" in smartphone2); // false
console.log("manufacturer1" in smartphone2); // true
console.log("manufacturer2" in smartphone2); // true
console.log("manufacturer3" in smartphone2); // true

값을 체크하는 것이 아니라 메소드와 프로퍼티를 확인하는 것에 사용하는 것이라는 것만 알면 어려울 게 없다.

 

 

6. for .. in & for .. of

쉽게 설명하자면 객체 순환과 배열 순환이다.

const ForIn = {
  a: 1,
  b: 2,
  c: 3,
  d: 4,
};

for (forIn in ForIn) {
  console.log(forIn);
}

//a
//b
//c
//d

for .. in을 사용할 경우 다음과 같이 객체를 순환하며 프로퍼티 값을 호출한다.

for .. of를 사용할 경우 에러가 나오며 정상적으로 호출되지 않는다.

 

const ForOf = ["a1", "a2", "a3", "a4"];
for (forof of ForOf) {
  console.log(forof);
}
// a1
// a2
// a3
// a4

for .. of를 사용할 경우 위와 같이 배열을 순환하며 값을 호출한다.

재미있는 점은 배열에서는 for .. in이 사용 가능하다.

 

const ForIn2 = ["a1", "a2", "a3", "a4"];
for (forin2 in ForIn2) {
  console.log(forin2);
}
// 0
// 1
// 2
// 3

우리가 지정하지는 않았지만 배열의 인덱스 값이 key로 지정되어 있는 것이나 마찬가지이므로 에러가 나오지 않고 정상적으로 출력되는 것을 볼 수 있다.

여기서 배운 for .. in을 활용해서 객체 복사까지 배워보자.

 

 

7. cloning (객체 복사)

const human = { name : 'ddoddi', sex : 'male', age : '7'}
const human2 = human;
human2.name = "babo"
console.log(human); // { name : 'babo', sex : 'male', age : '7' }
console.log(human === human2) // true

위의 방법이 기본적인 객체 복사 방법이며 이런 복사를 Shallow copy(얇은 복사)라고 부른다.

얇은 복사의 경우 복사한 객체와 기존 객체가 같은 레퍼런스를 가르키고 있기 때문에 복사한 개체에서 값을 수정하면 원본 객체도 같이 수정되며 동등 연산자를 사용해도 완전히 동일한 객체로 인식한다.

for .. in을 활용하면 이런 얇은 복사가 아니라 완전히 다른 객체를 만들어내는 deep copy(깊은 복사)를 할 수 있다.

 

const human = { name: "ddoddi", sex: "male", age: "7" };
const clonehuman = {};
for (data in human) { // for 객체 키를 빙글빙글 돈다~ in Human의
  clonehuman[data] = human[data];
}
console.log(clonehuman);
console.log(clonehuman === human); // false
clonehuman.name = "babo"; 
console.log(human); //{ name: "ddoddi", sex: "male", age: "7" }
console.log(clonehuman); //{ name: "babo", sex: "male", age: "7" }

for .. in을 활용해서 복사한 결과의 출력값을 보면 비교 연산자에서도 다른 객체로 인식하고 복사된 clonehuman의 값을 수정해도 원본 객체인 human에는 아무런 변화가 없는 것을 확인할 수 있다. 

사실 더더욱 간단한 방법도 존재한다! 바로 Object.assign()을 활용하는 방법이다. 위 코드에 이어서 바로 사용해보자.

clonevillain = Object.assign({}, clonehuman);
console.log(clonevillain); // { name: "babo", sex: "male", age: "7" }
console.log(clonevillain === clonehuman); // false

클론 빌런이 아주 간단하게 클론휴먼을 deep copy 해버린 것을 확인할 수 있다.