Frontend/JavaScript

[JS] Object 란?

:_: 2022. 4. 5. 18:07

 Literals and Properties

변수 하나당 값을 하나만 담을 수 있다.

출력하고 싶다면 하나씩 적어줘야 하는 번거러움이 있다. 그래서 object 를 사용한다.

 

object 만드는 방법

 

1. { } 를 사용해서 만들 수 있다. (ex. const obj1 = {} )  //  'object literal' syntax

2. new 키워드를 사용해 만들 수 있다. (ex. const obj2 = new Object();)   // 'object constructor' syntax

 

JS 에서는 클래스가 없어도  { } 를 이용해서 바로 object 를 만들 수 있다.

JS 동적으로 타입이 Runtime 때 결정되는 언어이다. 그래서 뒤늦게 하나의 변수를 추가,삭제 할 수 있다.

const person = {name: 'mark', age : 20};

// 추가
person.hasJob = true;
console.log(person.hasJob); // true

// 삭제
delete person.hasJob;
console.log(person.hasJob); // undefined

🌈 Object = { key : value};   // Object는 key와 value의 집합체이다.

 

Computed Properties (계산된 Properties)

object에 안에 있는 데이터에 접근할 때 .(dot)을 이용해 접근을 했는데

또 다른 방법은 ['property']와 같이 접근할 수 있다. 이 방법을 Computed Properties라고 한다.

console.log(person.name);
console.log(person['name']);

대괄호안에는 항상 String 타입으로 명시해주어야 확인이 가능하다.

 

중간에 변수를 추가하거나 삭제하는 것이 가능하다.

person['hasJob'] = true;
console.log(person.hasJob); // true

 

어떤 경우에 어떤 것을 쓸까요?

. 은 코딩하는 그 순간 키에 해당하는 값을 받아 오고 싶을 때 사용한다.

[ ] 은 정확하게 어떤 키가 필요한지 모를 때 사용한다.

 

Property value shorthand

const pserson1 = {name:'bob', age:2};
const pserson2 = {name:'steve', age:3};
const pserson3 = {name:'dave', age:4};
const pserson4 = makePerson('make', 30);

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

하나를 추가하고 싶을 때 일일이 작성하기엔 번거로움이 있다.

makePerson 함수를 만들어서 name,age 값을 받아서 함수 안에서  object 를 만들어서 return 

 

Constructor function

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

함수로 객체(object)를 만들때는 보통 앞의 문자를 대문자로 시작한다.

return을 통해 반환하지 않고 this를 사용한다.

함수를 호출할 때 new키워드를 사용해 호출한다.

 

this = {}와 return this;가 생략되어 있는 것이다.

 

In operator: property existance check( key in obj )

console.log(name in ellie);	// true
console.log(age in ellie);	// true
console.log(random in ellie);	// false

해당하는 object 안에 key 가 있는지 없는지 확인

 

For..in vs For..of

1) for (key in obj)

 obj 안에 있는 모든 키들을 맨 처음부터 하나씩 출력하게 됨

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

// 결과
   name
   age
   hasJob

 

2) for (value of iterable)

object가 아니라 배열을 사용

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

// 결과 
   1
   2
   4
   5

 

Fun Cloning

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

user2.name = 'coder'; 
console.log(user.name);  // coder

user2의 name을 바꿨지만 user의 name도 'coder'로 변경되어 있는 것을 볼 수 있다.
user2가 user과 같은 똑같은 ref를 가리키고 있기 때문이다.

 

📌 user2가 user를 참조하지 않고 똑같은 ref를 복사하는 방법

 

1. 예전에는 텅빈 객체를 만들고 for in 을 사용해서 복사하였다.

 

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

 

2. JS에 모든 객체는 Object에 상속되어 있으므로 Object.assign()를 통해 복사하는 것이 가능하다.

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

 

 

드림코딩 by 엘리 의 JS 강의를 시청 후 정리한 내용입니다.
728x90