본문 바로가기
JavaScript

[javaScript] zerocho 자바스크립트 강의 10강

by 박헹구 2021. 8. 19.
반응형

JSON

JSON 객체는 JavaScript Object Notation(JSON)을 분석하거나 값을 JSON으로 변환하는 메서드를 가지고 있습니다. JSON을 직접 호출하거나 인스턴스를 생성할 수 없으며, 두 개의 메서드를 제외하면 자신만의 흥미로운 기능은 없습니다.

JSON.parse() - 메서드는 JSON 문자열의 구문을 분석하고, 그 결과에서 JavaScript 값이나 객체를 생성합니다. 선택적으로, reviver 함수를 인수로 전달할 경우, 결과를 반환하기 전에 변형할 수 있습니다.

JSON.stringify() 메서드는 JavaScript 값이나 객체를 JSON 문자열로 변환합니다. 선택적으로, replacer를 함수로 전달할 경우 변환 전 값을 변형할 수 있고, 배열로 전달할 경우 지정한 속성만 결과에 포함합니다.

 

강의에서 제로초는 간단한 객체는 JSON.parse를 사용해도 크게 문제는 없지만 성능도 느리고 함수나 Math, Date같은 객체를 복사할 수 없다는 단점이 있다. 따라서 실무에서는 lodash안에 클론이라는 라이브러리(다른 사람이 미리 만들어 둔 코드)를 사용함.

 

https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/JSON

 

JSON - JavaScript | MDN

JSON 객체는 JavaScript Object Notation(JSON)을 분석하거나 값을 JSON으로 변환하는 메서드를 가지고 있습니다. JSON을 직접 호출하거나 인스턴스를 생성할 수 없으며, 두 개의 메서드를 제외하면 자신만

developer.mozilla.org

 

얕은 복사는 겉 껍데기만 복사하는 것. 

깊은 복사는 전부다 참조관계를 배낌.

const monster1 = JSON.parse(JSON.stringify(monsterList[0]); //깊은 복사
const monster3 = {...monster[0]}; // 얕은 복사

const arr = [...arr];  //객체의 얕은 복사

ex)

const a = [];
const b = 'heelo';
const c = {};

const arr1 = arr;

arr[1] = 'hi'
>> "hi"
arr[1]
>> "hi"

const arr2 = [...arr] //얕은복사
arr2[1] = 'babo';
>>"babo"
arr[1]
>> "hi"

arr2[0].push(1) //얕은복사는 가장 겉의 껍데기만 복사하고 내부의 객체는 참조가 된다. 
//내부의 참조를 끊어주고 싶으면 깊은 복사를 해주면된다
>>1
arr[0]
>> [1]

const arr3 =  JSON.parse(JSON.stringify(arr))
const array = [{j: 'k' }, {l: 'm'}];
const shallowCopy = [...array]; 얕은 복사
console.log(array === shallowCopy); //false
console.log(array[0] === shallowCopy[0]); //true

대표적인 얕은 복사로는 위의 방법과 
slice가 있다.

const reference = array; //참조
const deepCopy = JSON.parse(JSON.stringify(array)); //깊은 복사
console.log(array === reference); //true
console.log(array[0] === reference[0]); //true
console.log(array === deepCopy); // false
console.log(array[0] === deepCopy[0]); //false

객체안에 객체가 들어 있지 않으면 얕은 복사 함.

깊은 복사 하는 법

const hero = {
        name : '',
        lev : 1,
        maxHp: 100,
        hp : 100,
        xp: 0,
        att: 10,
        attack(monster) {
            monster.hp -= this.att;
            this.hp -= monster.att;
        },
        heal(monster) {
            this.hp += 20;
            this.hp -= monster.att;
        },
    };
    
    //this를 쓸때는 화살표 함수 X
    // 화살표 함수를 쓰면 this가 브라우저에서는 window가 되어버림.

this는 기본으로 window 객체를 가르키지만, 객체에서 this를 사용할 때는 해당 객체를 가리키게 됨.

객체.method를 해야지만 this가 그 객체가 된다.

 

클래스(class) - 객체를 생성하기 위한 템플릿(서식)이다. 이전에는 함수로 객체를 만들었으나 클래스라는 개념이 추가되었다.

class 예약어로 클래스를 선언하고, constructor 메서드 안에 기존 코드를 넣으면 된다. 클래스에 new를 붙여 호출하면 constructor 함수가 실행되고 객체가 반환됨. 여기서 this.는 생성된 객체 자신을 가르키게 됨.

class Monster {
constructor(name, hp, att, xp) {
	this.name = name;
    this.hp = hp;
    this.att = att;
    this.xp = xp;
    }
 }
 const monster1 = new Monster('슬라임', 25, 10, 11);
 const monster2 = new Monster('슬라임', 26, 10, 10);
 const monster3 = new Monster('슬라임', 25, 11, 10);

함수 선언문의 this 는 bind메서드를 사용해서 직접 바꿀 수 있다.

function a() {
console.log(this);
}
a.bind(document)(); //document

화살표 함수는 bind 사용 못함.

 

클래스 상속 

공통된건 묶어줄 수 있음.

 

 

반응형

댓글