
const obj1 = { }; // 'object literal' syntax → { }
const obj2 = new Object( ); // 'object constructor' syntax → class
Object = {key : value}; Object는 key와 value의 집합체이다
key should be always string key는 항상 string 타입이여야 한다
consol.log(sumni.name); → . → 그 key에 해당하는 값을 받아오고 싶을때
consol.log(sumni['name']); → [''] → 어떤 key가 필요한지 모를때 (runtime에서 결정될때)
const person1 = {name: 'bob', age: 2};
const person2 = {name: 'steve', age: 3};
const person3 = {name: 'dave', age: 4};
const person4 = {name: ' '}; > makePerson('sumni', 7);
function makePerson(name, age) {
return {
name: name,
age: age,
};
}
JS에는 Property value shorthand라는 기능이 있어서 key와 value의 이름이 동일하다면 위에 name:, age: 생략가능
makePerson은 class 즉, 템플릿 같은 기능 > JS에 class기능이 없을때 사용
다른 계산을 하지않고 순수하게 object만 사용하는 것은 보통 대문자(Person)로 시작하도록 함수를 만듦, return을 사용하지 않고 this.(name) 를 사용, new (Person) 사용 → new는 class (이 부분 다시 확인해보기!)
const person1 = {name: 'bob', age: 2};
const person2 = {name: 'steve', age: 3};
const person3 = {name: 'dave', age: 4};
const person4 =new Person('sumni', 7);
console.log(person4);
function Person(name, age) {
// this = { };
this.name = name;
this.age= age;
// return this;
}
in operator는 해당하는 오브젝트안에 key가 있는지 없는지 확인하는것
console.log('name' in sumni);
console.log('age' in sumni);
console.log('random' in sumni);
console.log(sumni.random); → 없는 부분은 undefined
//for (key in obj) obj가 가지고 있는 key들이 블럭을 돌때마다 key라는 지역변수에 할당
for (key in 00) { 모든 key들을 받아서 일들을 처리하고싶을때 사용)
console.log (key);
}
// for (value of iterable) → 배열 list사용 (순차적으로 데이터가 담긴것)
const array = [1, 2, 4, 5];
bad ver.
for(let i = 0; i < array.length ; i++) {
console.log(array[i]);
good ver.
for(value of array) { (array에 있는 모든값들이 value에 할당되면서 블럭안에서 순차적으로 출력하거나 값을 계산할수 있음)
console.log(value);
}
//Object.assign(dest, [obj1, obj2, obj3...])
const user = {name: 'sumni', age: '20' };
const user2 = user;
user2.name = 'ari';
console.log(user); > sumni가 ari로 바뀜
//old way
const user3 = { };
for (key in user) {
user3[key] = user [key];
}
console.clear( );
console.log (user3); > 다시 sumni로 되는것을 확인할수 있음
복사하고자 하는 타겟과 복사를 하려고하는 소스를 같이 전달해줘야함
리턴값은 타겟과 복사하고자 하는값이 통합된 값
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);
console.log(mixed.color);
console.log(mixed.size);
color: blue, size: big
뒤에나오는 값이 있을 경우 앞에있는 값에 덮어씌워지기 때문에 뒷값이 나오게됨
객체 지향 언어에 대해 더 공부하기!