JavaScript/드림코딩 엘리 - 자바스크립트 기초 강의 (ES5+)
드림코딩 엘리 - 자바스크립트 기초 강의(ES5+) (7편)
정ㅇr
2021. 11. 15. 23:20
728x90
Object
// 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 };, object는 key와 value의 집합체이다
// 1. Literals and properties
// Object를 만드는 방법
const obj1 = {}; // 'object literal' syntax
const obj2 = new Object(); // 'object constructor' syntax
function print(person) {
console.log(person.name);
console.log(person.age);
}
const ellie = { name: 'ellie', age: 4 };
print(ellie);
ellie.hasJob = true;
console.log(ellie.hasJob);
// with JavaScript magic (dynamically typed language)
// can add properties later
delete ellie.hasJob;
console.log(ellie.hasJob);
// 2. Computed properties : runtime에서 결정될 때 사용함
// key는 string 타입으로 지정해서 받아와야 한다.
console.log(ellie.name); // 보통 코딩할 때는 이 방식으로
console.log(ellie['name']);
ellie['hasJob'] = true;
console.log(ellie.hasJob);
// 예시
function printValue(obj, key) {
console.log(obj[key]);
}
printValue(ellie, 'name');
// 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('ellie', 30);
console.log(person4);
// 값만 전달해주면 object를 만들어주는 함수 생성
// 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), true / false 리턴함
console.log('name' in ellie);
console.log('age' in ellie);
console.log('random' in ellie);
// 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(value of array) {
console.log(value);
}
// 7. Fun cloning
// Object.assign(dest, [obj1, obj2, obj3...])
const user = { name: 'ellie', age: '20' };
const user2 = user;
console.log(user);
// old way
const user3 = {};
for (key in user) {
user3[key] = user[key];
}
console.clear();
console.log(user3);
// new way
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);
// 동일한 properties를 가지고 있다면 맨 뒤에 나오는 배열의 값으로 복사됨
console.log(mixed.color);
console.log(mixed.size);
출처
https://www.youtube.com/watch?v=1Lbr29tzAA8&list=PLv2d7VI9OotTVOL4QmPfvJWPJvkmv6h-2&index=7&ab_channel=%EB%93%9C%EB%A6%BC%EC%BD%94%EB%94%A9by%EC%97%98%EB%A6%AC
반응형