JavaScript/기본 내장 객체

Object 객체

유혁스쿨 2022. 1. 19. 17:30
728x90
반응형

object 객체는 자바스크립트의 최상위 객체이다.

 

자바스크립트의 가장 기본적인 내장 객체는 Object 객체로 정확히는 Object 생성자 함수로 만든 인스턴스지만 간단하게 Object 객체라고 표현한다.

 

Object객체 생성

var object = {};
var object = new Object();

 

Object객체의 메서드

constructor( ) : 객체의 생성자 함수를 나타낸다.

hasOwnProperty( ) : 객체가 name속성이 있는지 확인한다.

isPrototypeOf( ) : 객체가 object의 프로토타입인지 검사한다.

propertyIsEnumerable( ) : 반복문으로 열거할 수 있는지 확인한다.

toLocaleString( ) : 객체를 호스트 환경에 맞는 언어의 문자열로 바꾼다.

toString( ) : 객체를 문자열로 바꾼다.

valueOf( ) : 객체의 값을 나타낸다.

 

 

자바스크립트의 모든 기본 내장객체는 Object 객체를 기본으로 만들어지기 때문에 자바스크립트의 모든 내장 객체에는 위와 같은 Object 객체의 일곱가지 메서드를 공용으로 갖는다.

 

 

hasOwnProperty() 와 propertyIsEnumerable()

var object = { property : 273 };
var output = '';
output += "HOP('property'): " + object.hasOwnProperty('property') + '\n';
output += "HOP('constructor'): " + object.hasOwnProperty('constructor') + '\n';
output += "PIE('property'): " + object.propertyIsEnumerable('property') + '\n';
output += "PIE('constructor'): " + object.propertyIsEnumerable('constructor') + '\n';

for(var key in object){
    console.log(object[key]);
}

두개의 메서드를 통해 property 속성을 검사한것은 모두 true를 출력하고 constructor 속성을 검사한 것은 모두 false를 출력한다.

또한 propertyIsEnumerable 메서드를 true로 가지는 속성만 for in 반복문으로 출력한다.

 

 

toString( )

객체를 문자열로 반환하는 메서드이다.

var object = new Object();

console.log(object);
console.log(object.toString());

toString( ) 메서드는 객체를 문자열로 변환할 때 자동으로 호출된다.

var student = {
    name : '남궁찬'
    grade : '대학교 졸업'
    toString : function () {
        return this.name + ' : ' + this.grade;
    }
};

alert(student);

자바스크립트에서 모든 객체는 toString( ) 메서드를 가지는데, 다시 선언했으므로 재선언한 것이다.

 

 

 

constructor( ) 메서드

객체의 생성자 함수를 의미한다.

 

Number 혹은 String 객체에서 typeof연산자로 자료형을 검사하면 문제가 발생할 때가 있다.

그 예시는 다음과 같다.

var numberLiteral = 273;
var numberConstructor = new Number(273);

console.log(typeof numberLiteral, typeof numberConstructor)

두 변수 모두 숫자지만 생성자 함수로 만든 숫자는 객체이므로 이러한 결과가 나온다.

 

var stringLiteral = 'Hello world';
var stringConstructor = new String('Hello world');

console.log(typeof stringLiteral, typeof stringConstructor)

문자열 객체 String 에서도 동일한 결과를 확인할 수 있다.

var numberLiteral = 273;
var numberConstructor = new Number(273);

if (typeof numberLiteral == 'number'){
    alert('numberLiteral은 숫자이다.');
}else if (typeof numberConstructor == 'number'){
    alert('numberConstructor은 숫자이다.');
}

두 변수 모두 숫자이지만 생성자 함수로 만든 숫자는 Object 객체이므로 경고창을 출력하지 않는다.

 

이렇게 두 대상을 같은 자료형으로 취급하고 싶을 때는 constructor( ) 메서드를 사용해야 한다.

var numberLiteral = 273;
var numberConstructor = new Number(273);

if (typeof numberLiteral.constructor == Number){
    alert('numberLiteral은 숫자이다.');
}else if (typeof numberConstructor.constructor == Number){
    alert('numberConstructor은 숫자이다.');
}

숫자와 문자열 객체를 생성하는 new Number(숫자) 혹은 new String('문자열') 은 숫자 혹은 문자를 반환하는게 아니라 Number 혹은 String객체의 참조 주소(메모리 주소)를 반환하기 때문이다.

더 풀어서 말하자면 일반 리터럴 변수에 저장된 숫자 혹은 문자열은 숫자 혹은 문자열 그 자체의 상태로 메모리영역에 저장되지만

Number 혹은 String 객체의 생성자를 사용한 숫자는 Object타입으로 (업캐스팅) 메모리영역에 저장되는것이다.

때문에 둘은 다른 형태의 타입이라고 말할 수 있다.

 

 

객체에 메서드 추가

 

Object 객체는 모든 자바스크립트의 최상위 객체이기 때문에 Object 객체의 프로토타입에 속성 또는 메서드를 추가하면 모든 객체에서 활용할 수 있다.

 

Object.property 객체에 test( ) 메서드를 추가한다.

Object.prototype.test = function () {
    alert(this);
};

var number = 273;
number.test();

이렇게 메서드를 추가하면 자바스크립트의 모든 객체에서 test( ) 메서드를 사용할 수 있게된다.

728x90
반응형