TIL no.20 - JS 객체(Object)

김종진·2020년 12월 25일
0

JavaScript

목록 보기
11/18

객체(Object)

JavaScript는 객체기반의 스크립트 언어로 객체란 여러 가지 속성을 하나의 변수에 저장 할 수 있는 데이터 타입이다.

let jin = {
	firstName = "Kim",
    	lastName = "Jongjin",
   	age = 30
};

저의 간단소개를 객체로 만들어 봤습니다.

객체의 특징

  • 객체는 변수로 여러가지 값이 포함될 수 있다.

  • {} 표기를 이용하여 각각의 key/value에 대한 정보를 나열할 수 있다.

  • Key는 문자열 또는 기호, Value는 모든 유형이 될 수 있다.

  • 객체에서 정의한 값을 속성(Property)이라고 한다.
    객체 이름에 . 을 찍어서 접근 할 수 있다.
    Properties값으로 함수가 올 수 있는데 이를 메소드(method)라고 합니다.

  • 자바스크립트에서 숫자, 문자, Boolean, null, undefined 타입을 제외한 모든 것이 객체이다.
    (숫자, 문자, Boolean은 객체가 될 수 있다.)

객체 생성 방법

1. 객체 리터럴 방식

let jin = {
	firstName = "Kim",
    	lastName = "Jongjin",
   	age = 30
};

2. 생성자 함수 이용

const person = new Person('jongjin', 30); // person 객체 생성
console.log(person); // Person {name: "jongjin", age: 30}

// Person() 생성자 함수
function Person(name, age) { 
    this.name = name;
    this.age = age;
}

in operator

해당 속성이 객체에 있는지 판별해줍니다.

console.log('age' in jin) // true
console.log('power' in jin) // false

for in

객체 안에 있는 속성들을 나열해줍니다. (Key 값에 접근)

for (key in jin) {
	console.log(key); //name , age
}

for of

Symbol.iterator 속성을 가지는 컬렉션의 값들을 나열해줍니다.

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

객체 복사

const user = { name: 'jongjin', age: '30'};
const user2 = user;
user2.name = "shenghyen"
console.log(user); // {name: "shenghyen", age: "30"}

우선 이렇게 그대로 변수에 담아버리고 나중에 원본을 불러오면 원본 값이 바뀌어 버리게 때문에 좋지 않다.

const user = { name: 'jongjin', age: '30'};
const user2 = Object.assign({}, user);
console.log(user); // { name: 'jongjin', age: '30'};

위와 같은 상황을 방지하기 위해서 우선 새로운 변수에 빈 객체를 만들고 복사할 객체를 할당해주면 된다.

const Balloon1 = { color: 'red'};
const Balloon2 = { color: 'blue', size:'big'};
const mixed = Object.assign({}, Balloon1, Balloon2);
console.log(mixed.color); // blue
console.log(mixed.size); // big

또다른 예시로 여러개의 객체를 하나로 복사할 때 맨 뒤에있는 속성값을 기준으로 덮어서 복사되어진다.

참고한 강의
드림코딩 by 엘리
TCPschool

profile
FE Developer

0개의 댓글