하다보니

object 본문

프로그래밍 언어/JavaScript

object

claire 2022. 1. 16. 12:23
// 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 - new로 정의하면 object에서 정의된 constructor 호출

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)
//뒤늦게 property를 추가할 수 있다. 
// can add properties later
//너무 동적으로 코딩하면 나중에 유지보수하기 힘들고 생각하지 못한 오류도 나와서 피하는게 좋다. 
ellie.hasJob = true;
console.log(ellie.hasJob);

// can delete properties later
delete ellie.hasJob;
console.log(ellie.hasJob);
// 2. Computed properties
// key should be always string
console.log(ellie.name);  //코딩하는 순간 해당 키의 값을 받아오고 싶을 때 쓴다. 
console.log(ellie['name']);	//이렇게 대괄호로 받아오는 것이 computed properties이다. 
//정확하게 어떤 키가 필요한지 모르고 런타임에서 결정될 때 쓴다. 
//코딩할때는 .을 쓰는 것이 맞다. 
ellie['hasJob'] = true;
console.log(ellie.hasJob);

//key가 어떤 것인지 아래 코드를 코딩하는 순간엔 모른다. 따라서 computed properties를 써야한다.
//동적으로 키에 관련된 value를 받아와야할때 유용하게 쓰인다.
//아래와 같이 .을 쓰게 되면 obj에 key라는 property가 들어있냐는 질문과도 같다. 
function printValue(obj, key) {
  console.log(obj.key);			//undefined 출력
}

function printValue(obj, key) {
  console.log(obj[key]);
}
printValue(ellie, 'name');
printValue(ellie, 'age');
// 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);  
//const person4=makePerson('ellie',30);
console.log(person4);


//오브젝트 생성하는 함수 - js에 클래스가 없을 때 많이 사용이 되었다. 
function makePerson(name,age){
  return{		
  	name,		//js에는 property value shorthand라는 기능이 있어서 key와 value의 변수값이 같다면 하나 생략 가능하다. 
    age,
  };
}

// 4. Constructor Function
//다른 계산을 하지 않고 순수하게 오브젝트를 생성하는 함수들은 대문자로 시작하고 this를 써서 작성한다.
//new를 써서 호출한다. 
function Person(name, age) {  
  // this = {}; //this라는 오브젝트 만듦. 생략됨
  this.name = name;
  this.age = age;  
  // return this; //this를 리턴
}
// 5. in operator: property existence check (key in obj)
//해당 오브젝트 안에 key가 있는지 확인하는 것 t/f로 출력
console.log('name' in ellie);	//true
console.log('age' in ellie);	//true
console.log('random' in ellie); //false
console.log(ellie.random);   //정의되지 않는 키의 값을 출력하면 undefined이 나온다.  

// 6. for..in vs for..of
// for (key in obj)
//오브젝트에서 사용
for (let key in ellie) {
  console.log(key);
}

// for (value of iterable)
//object가 아닌 순차적으로 데이터가 담겨있는 iterable한 객체를 대상으로 한다. 
const array = [1, 2, 4, 5];
for (let value of array) {
  console.log(value);
}
// 7. Fun cloning
//얕은 복사
const user = { name: 'ellie', age: '20' };
const user2 = user;
user2.name='coder';
console.log(user.name);  //name:coder로 출력

//object를 완전히 복사하는 방법
// old way
const user3 = {};  //빈 오브젝트에 넣는 방법
for (let key in user) {
  user3[key] = user[key];
}

console.log(user3);

// Object.assign(dest, [obj1, obj2, obj3...])
//Object는 js에 기본 탑재되어있는 오브젝트 중에 하나. 모든 오브젝트는 이 Object를 상속한다. 
//assign은 (복사할 곳,복사할 값)이 인자로 주어진다. 
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);   //동일한 property가 있을 경우 뒤에 나오는 것이 앞의 것을 덮어씌운다. 
console.log(mixed.color); //blue
console.log(mixed.size);  //big

 

참고 : 드림 코딩 by 엘리