[ javascript ] object 생성, 사용방법 > javascript&jQuery

본문 바로가기

사이트 내 전체검색

javascript&jQuery

[ javascript ] object 생성, 사용방법

작성일 21-02-14 00:01

페이지 정보

작성자 웹지기 조회 1,263회 댓글 0건

본문

'use strict';
객체(Objects)
//one of the JavaScript's data types.
//a collection of related data and/or functionality.
//Nearly all objects in JavaScript are instances of Objets.
//object = { key : value }; 
//오브젝트는 키와벨류의 집합체
//변수에 접근가능한 property 와 값의 집합

1. 변수에 넣은 변하지 않는 데이터와 속성(Literals and properties)
//const name = 'test';
//const age = 10;
//print(name, age);
function print(person) {
    console.log(person.name);
    console.log(person.age);
}

const test = {name:'test', age:14};
print(test);

//object 정의 2가지 방법
const obj1 = {}; //'object literal' syntax
const obj2 = new Object(); //'object constructor' syntax

//유지보수에 어려운 코딩방법
//test.hasJob = true; //이런식으로 object를 만들지 말자
//console.log(test.hasJob);
//이런식으로 바로 삭제도 가능하다.
//delete test.hasJob;
//console.log(test.hasJob);  //결과 -> undefined

2. 계산된 속성(Computed properties)
//배열의 형태로 적고 ''로 스트링타입으로 불러온다.
//동적으로 키의 값을 가져올 때 사용하기 유용
console.log(test.name);
console.log(test['name']);

test['hasJob'] = true;
console.log(test.hasJob);

function printValue(obj, key){
    //이런형태로 값이 변경되는 구문에서는 . 을 통해서 값을 가져오면 undefined가 출력
    console.log(obj.key); 
    //대신 computed properties를 사용하면 정상적 출력가능
    console.log(obj[key]);
}
printValue(test, 'name');
printValue(test, 'age');

3. 속성값 빠른 정의(Property value shorthand)
//일일이 적어서 넣어주었던 번거로움을 함수를 통해 쉽게 넣어 줄 수 있다.
const person1 = {name:'bob', age:2};
const person2 = {name:'steve', age:3};
const person3 = {name:'hahaha', age:13};

/*
이렇게 함수를 만들어서 사용하는 부분을 클래스인것처럼 작성을 하게 되면
알아서 클래스 처럼 받아들여서 사용을 할 수 있게 해준다.
const person4 = makePerson('kikiki', 23);
console.log(person4);
function makePerson(name, age) {
    return {
        //키와 벨류의 이름이 동일하면 이것을 생략할 수가 있다.
        //name : name,
        //age : age,
        //이런식으로 생략이 가능.
        name,
        age,
    };
}
*/

3번 에서 사용되는 함수의 변형이 4번
4. 생성자 기능(Constructor Function)
const person4 = new Person('kikiki', 23);
console.log(person4);
function Person(name, age){
    //this = {}; //이부분이 생략되어 있다고 보면 됩니다.
    this.name = name;
    this.age = age;
    //return this;
    //return 구문 역시 생략되어 자동으로 this를 return해준다
}

5. in키워드를 이용해서 키의 오브젝트 확인(in operator : property existence check(key in obj));
console.log('name' in test);
console.log('age' in test);
console.log('random' in test);
console.log(test.rendom);

6. for..in vs for..of
//for(key in obj);
console.clear();//console창 청소
console.log(test.name);
console.log(test.age);
for(const key in test) {
    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구문으로 출력했던 것을
아래처럼 for of를 통해 간단히 출력가능
*/
for(const value of array) {
    console.log(value);
}

7. 객체복제(Fun cloning)
//객체에 객체를 복사한 후 복사한 객체의 값을 바꾸게 되면
//최초 넣어둔 객체의 값도 바뀌게 된다.
//Object.assign(dest, [obj1, obj2, obj3....])
const user = {name:'test', age:20};
const user2 = user;
user2.name = 'coder';
console.log(user);

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

Object를 이용한 복제
//첫번째 복사 방법
const user4 = {};
Object.assign(user4, user); 
console.log(user4);
//두번째 복사 방법
const user5 = Object.assign({}, user);
user5.name = 'aaaa';
console.log(user5);

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


추천0

비추천 0

댓글목록

등록된 댓글이 없습니다.

전체 63건 1 페이지

이미지 목록

게시물 검색
Copyright © 즐거운 코딩 생활 ( funyphp ). All rights reserved.
PC 버전으로 보기