JavaScript
래퍼 객체
마라랑랑
2022. 5. 23. 04:03
래퍼 객체는 래퍼라는 이름에서 알 수 있듯이 래퍼 객체는 원시 타입을 감싸는 형태로 사용된다.
const bool = false;
const num = 123;
const str = 'string';
const bool2 = new Boolean(false);
const num2 = new Number(123);
const str2 = new String('string');
원시값(위) 원시값의 래퍼 객체(아래)
console.log(bool); false
console.log(bool2); Boolean false {}
console.log(typeof bool); boolean
console.log(typeof bool2); object
래퍼객체를 사용시 값을 바꿀 수 없는 특징이 사라지지만 불편함이 생긴다.
console.log(bool2 instanceof Boolean); true
console.log('string' instanceof String); false
console.log(str2 instanceof String); true
메모리 주소가 다르기 때문에 false가 나온다.
래퍼객체를 사용시 근본적으로 다른 구조가 되기 때문에 사용을 지양해야한다.
const bool2 = new Boolean(false).valueof();
const num2 = new Number(123).valueof();
const str2 = new String('string').valueof();
valueof() 사용시 래퍼객체를 다시 원시값으로 되돌릴 수 있다.