[JS] 객체(Object)

Pyo·2023년 11월 13일
0

Dart에서의 보통 객체를 class의 생성자를 이용하여 생성하거나 , Map을 이용하여 생성하였는데 자바스크립트에서는 객체 리터럴을 이용하여 생성하면 데이터타입이 Map이아닌 Object였기 때문에 헷갈렸다. 그래서 객체에 대한 정리를 따로 해보려고 한다.
Dart와 비교하면서 공부를 해보니 Dart언어를 사용하면서 그냥 지나쳤던 개념들도 제대로 짚고 넘어갈수 있는것 같다.

객체(Object)

자바스크립트의 객체는 데이터의 집합으로, 키(key)과 값(value)으로 구성된 프로퍼티(Property)들을 포함하는 컨테이너다.

객체 생성 방법

객체의 생성 방법은 크게 세가지로 나뉜다.

  • 객체 리터럴
let fruits1 = {
    name : 'strawBerry',
    color : 'red',
    size : 'small',
    myInfo : function () {
        console.log(`나는 ${this.name} 입니다.`);
    } 
}
  • Object
let fruits2 = new Object();

fruits2.name = 'banana';
fruits2.color = 'yellow';
fruits2.size = 'middle'
fruits2.myInfo = function() {
    console.log(`나는 ${this.name} 입니다.`);
}
  • 생성자 함수
class Fruits {
    constructor(name,color,size){
        this.name = name;
        this.color = color;
        this.size = size;
    }
    myInfo() {
        console.log(`나는 ${this.name} 입니다.`);
    }
}

let fruits3 = new Fruits('melon','green','big');

객체의 내부 상태 변경

let fruit = {
    name : 'strawBerry',
    color : 'red',
    size : 'small',
    myInfo : function () {
        console.log(`나는 ${this.name} 입니다.`);
    } 
}
  • 객체의 프로퍼티 값 읽기
console.log(fruit.name); 	// strawBerry
console.log(fruit['name']); // strawBerry
  • 객체의 프로퍼티 값 변경
fruit.color = 'blue';	
console.log(fruit.color);	// blue
  • 객체의 프로퍼티 값 삭제
delete fruit.color;
console.log(fruit);	
// { name: 'strawBerry', size: 'small', myInfo: [Function: myInfo] }
  • 객체의 프로퍼티 값 추가
fruit.color = 'red';
console.log(fruit.color); 
// { name: 'strawBerry', size: 'small', myInfo: [Function: myInfo], color: 'red' }

객체의 불변성 유지

객체의 불변성이 유지 되어야 하는 이유는 원본 데이터가 변경, 훼손되는 것을 막을 수 있기 때문이다. Object의 메서드인 preventExtensions(),seal(),freeze()를 이용하면 객체의 불변성을 유지 할수 있다.

class Fruits {
    constructor(name,color,size){
        this.name = name;
        this.color = color;
        this.size = size;
    }
}

preventExtendsions()

let melon = new Fruits('melon','green','big');

console.log(Object.isExtensible(melon)); // true
melon.taste = 'sweet';
console.log(melon); // Fruits { name: 'melon', color: 'green', size: 'big', taste: 'sweet' }
 

Object.preventExtensions(melon);
melon.isSeed = true;
console.log(melon); // Fruits { name: 'melon', color: 'green', size: 'big', taste: 'sweet' }


delete melon.taste;
console.log(melon); // Fruits { name: 'melon', color: 'green', size: 'big' }
  • 객체에 새로운 프로퍼티의 추가를 금지한다.

  • 이미 존재하는 프로퍼티의 값은 수정할 수 있다.

  • 이미 존재하는 프로퍼티를 삭제하는 것은 가능하다.

    seal()


let melon = new Fruits('melon','green','big');
console.log(Object.isSealed(melon)); // false

Object.seal(melon);
console.log(Object.isSealed(melon)); // true

melon.taste = 'sweet';
console.log(melon);	// Fruits { name: 'melon', color: 'green', size: 'big' }


delete melon.size;
console.log(melon);	// Fruits { name: 'melon', color: 'green', size: 'big' }


Object.defineProperty(melon,'color',{
    value : 'blue'
});
console.log(melon);	// Fruits { name: 'melon', color: 'blue', size: 'big' }
  • Object.seal()은 Object.preventExtensions()의 특성을 포함하며, 추가로 존재하는 프로퍼티의 삭제를 금지합니다.

  • 이미 존재하는 프로퍼티의 값은 수정할 수 있습니다.

    freeze()

let melon = new Fruits('melon','green','big');
console.log(Object.isFrozen(melon)); // false
Object.freeze(melon);
console.log(Object.isFrozen(melon)); // true

melon.taste = 'sweet';
console.log(melon);	// Fruits { name: 'melon', color: 'green', size: 'big' }


delete melon.size;
console.log(melon); // Fruits { name: 'melon', color: 'green', size: 'big' }

// 변경이 불가능 하여 에러 발생
Object.defineProperty(melon,'color',{
    value : 'blue'
});
  • Object.freeze()는 Object.seal()의 특성을 포함하며, 추가로 이미 존재하는 프로퍼티의 값 수정도 금지합니다.
  • 객체가 완전히 고정되어 더 이상 변경되지 않습니다.

객체 안에 객체의 경우 상우 오브젝트에만 적용이 되고 , 하위 오브젝트에는 적용되지 않는다.

0개의 댓글

관련 채용 정보