/**
* Objects
* one of the JavaScript's data types.
* a collection of related data and/or functionality.
* Nearly all objects in JavaScript are instance of Object
* Object = {key : value};
*/
// 1. Literal and properties
const name = 'ellie';
const age = 4;
print(name,age);
function print(name, age){
console.log(name);
console.log(age);
} //고루고루 하기 어려워 진다!!
function prints(person){
console.log(person.name);
console.log(person.age);
} //고루고루 하기 어려워 진다!!
const ellie = {name: 'ellie', age:4};
prints(ellie);
const obj1 ={}; //'object literal' syntax
const obj2= new Object(); //'object constructor' syntax
ellie.hasJob = true; //동적으로 추가가 가능함!! (지양)
console.log(ellie.hasJob);
delete ellie.hasJob; //삭제도 가능함!!
console.log(ellie.hasJob);
// 2. Computed properties
console.log(ellie.name); //정확히 알떄
console.log(ellie['name']); // 정확하게 어떤 키인지 모를떄
//배열 처럼 작동 가능!! (String으로 지정!)
ellie['hasJob'] = true;
console.log(ellie.hasJob);
//ex
function printValue(obj, key){
//console.log(obj.key); //undefined
console.log(obj[key]); //ellie
}
printValue(ellie, 'name');
printValue(ellie, 'age');
//3. Property value shorthand
const person1 = {name : 'bob', age: 2};
const person2 = {name : 'steve', age: 2};
const person3 = {name : 'dave', age: 2};
const person4 = makePerson('ellie',30);
const person5 = new Person('ellie',30);
console.log(person4); //정상
function makePerson(name,age){
return{
name,
age,
};
}
// 4. Constructor function
function Person(name, age){
// this = {}
this.name = name;
this.age = age;
//return this;
}
//5. in operator : property existence check (key in obj)
console.log('name' in ellie); //true
console.log('age' in ellie); //true
console.log('random' in ellie); //false
//6. for..in vs for ..of
// for (key in obj)
console.clear(); //정리
for (key in ellie) {
console.log(key);
}
// for (value of iterable)
const array = [1,2,4,5];
for (let i = 0; i< array.length; i++){
console.log(array[i]);
}
for(value of array) {
console.log(value);
}
// 7. Fun Cloning
// Object.assign (dest, [obj1, obj2, obj3...])
const user = { name : 'ellie', age: '20'};
const user2 = user;
user2.name = 'coder';
console.log(user);
//old key
const user3 = {};
for (key in user){
user3[key] = user[key]; //빙글빙글 복사!!
}
console.clear();
console.log(user3);
//new way
const user4 = {};
Object.assign(user4, user);
console.log(user4);
const user5 = Object.assign({}, user);
console.log(user5);
//another example
const fruit1 = {color: 'red'};
const fruit2 = {color: 'blue', size:'big'};
const fruit3 = {color : 'yellow'};
const mixed = Object.assign({},fruit1, fruit2,fruit3); //계속 덮어쓴다!!
console.log(mixed.color);
console.log(mixed.size);
출처 : 드림코딩 엘리
반응형
'Develope_Web_Programming > 01_HTML&CSS&JS' 카테고리의 다른 글
9. 유용한 10가지 배열 함수들 (0) | 2021.02.14 |
---|---|
8. 배열 제대로 알고 쓰자 (0) | 2021.02.14 |
6. 클래스와 오브젝트의 차이 (0) | 2021.02.13 |
5. Arrow Function은 무엇인가? (0) | 2021.02.13 |
4. 코딩의 기본 operator, if, for loop (0) | 2021.02.13 |
Uploaded by Notion2Tistory v1.1.0