동캄의 코딩도장

JS [Object] 본문

front/HTML&CSS&JS

JS [Object]

동 캄 2022. 1. 24. 00:46
// 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

function print(person){
    console.log(person.name);
    console.log(person.age);
}

const ellie ={name:'ellie', age:4};
print(ellie);

// JS는 runtime에서 동작하므로 dynamic 코딩이 가능함

ellie.hasjob =true;
console.log(ellie.hasjob);

delete ellie.hasjob;
console.log(ellie.hasjob);

// 2. Computed properties

//key should be always 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');
printValue(ellie,'age');

//3. Propery value shorthand

const person1 = {name:'bob',age:2};
const person2 = {name:'bobi',age:3};
const person3 = {name:'apple',age:4};
const person4 = new Person('ellie',30);

// 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);
console.log('age' in ellie);
console.log('random' in ellie);
console.log(ellie.random);

// 6. for..in vs for..of
// for (key in obj)

for (let 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.assing(dest, [obj1, obj2, obj3 ...])
const user = {name:'ellie', age:20};
const user2=user;
user2.name='coder';
console.log(user);

//old way
const user3 ={};

for (key in user){
    user3[key]=user[key];
}
console.log(user3);

//recently used way
const user4 = Object.assign({},user);

// 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);

'front > HTML&CSS&JS' 카테고리의 다른 글

JS [array API]  (0) 2022.01.24
JS [array]  (0) 2022.01.24
JS [Class]  (0) 2022.01.24
JS [function]  (0) 2022.01.23
JS [operators]  (0) 2022.01.23