JavaScript String 객체와 constructor 속성
JavaScript에서 String 객체를 다룰 때 constructor 속성은 매우 유용한 정보를 제공합니다. 이 속성은 해당 인스턴스의 프로토타입을 생성한 원본 함수에 대한 참조(reference)를 반환하며, 이를 통해 객체가 어떤 생성자 함수로부터 만들어졌는지 확인할 수 있습니다.
string.constructor의 역할
string.constructor는 String 객체의 타입 출처를 파악하게 해주는 속성입니다. 일반적으로 String 객체에 접근하면 function String() { [native code] } 형태의 참조 값이 반환됩니다. 이는 자바스크립트 내장(built-in) String 생성자 함수를 의미합니다.
예제 코드
아래 예제를 실행하면 new 키워드로 생성한 String 객체의 constructor 값을 직접 확인할 수 있습니다.
<html>
<head>
<title>JavaScript String constructor Method</title>
</head>
<body>
<script>
var str = new String("This is string");
document.write("str.constructor is:" + str.constructor);
</script>
</body>
</html>
실행 결과
위 코드를 브라우저에서 실행하면 다음과 같은 출력 결과를 얻을 수 있습니다.
str.constructor is:function String() { [native code] }이처럼 constructor 속성을 활용하면 객체가 어떤 생성자 함수에서 비롯되었는지 명확히 파악할 수 있어, 디버깅이나 타입 검증 작업 시 큰 도움이 됩니다.