자바스크립트 내장 객체에는 다양한 객체들이 존재하는데, 이중 Number객체, String 객체, Array 객체, Math 객체, Date 객체를 많이 이용합니다.

먼저, 내장 객체를 생성하기 위해서 new 키워드를 정의해주기만 하면 됩니다.

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

객체에는 다음의 표를 사용할 수 있습니다.

메서드 설 명
constructor 객체의 생성자를 반환
hasOwnProperty(name) 객체에 name 속성이 있는지 검사
이름이 있으면 true, 아니면 false
isPrototypeof(object) 객체가 프로토타입인지 검사
propertyLsEnumerable(name) 반복문으로 열거할 수 있으면 true, 아니면 false
toLocaleString() 객체를 서버 환경에 맞는 언어의 문자열로 변환
toString() 객체를 문자열로 변환
valueOf() 객체의 값

<script>
var obj = {name: "hello"};

if(obj.hasOwnProperty("name")){
  document.write("이름이 있습니다.");
}
if(!obj.hasOwnProperty("age")){
  document.write("나이가 없습니다.");
}

// 객체를 문자열로 바꿉니다.
var name = obj.name.toString();
document.write(name);

// name 값을 얻습니다.
var val = obj.name.valueOf();
document.write(val);
</script>

객체에 값을 저장하려면 이름과 값의 형식으로 저장하면 됩니다.

<script>
var obj = new Object();

obj.name = "하보니";
obj.age = 20;
obj.job = "하보니 PHP";

// 출력할 때는 이렇게...
document.write(obj.name + "<br/>");
document.write(obj.age + "<br/>");
document.write(obj.job + "<br/>");
</script>


프로토타입

Object 객체는 객체 중에서 가장 기본이 되는 객체이며, 최상위 객체이기 때문에 Object 객체의 프로토타입에 속성이나 메서드를 추가해 주면 모든 객체에 메서드를 추가할 수 있습니다.

<script>
Object.prototype.habony = function(){
  document.write(this);
}

var str = "안녕 하보니";
str.habony(); // 안녕 하보니
</script>

<script>
function myPrototype(){
  return "프로퍼티: " + this.habony;
}
var obj = new Object;
obj.habony = "Hello Habony";
obj.Proto = myPrototype;

document.write( obj.Proto() ); // 프로퍼티: Hello Habony
</script>

아래 예시를 통해 함수도 실은 하나의 객체라는 사실을 알 수 있습니다.

<script>
function proto(a, b){
  this.key = "key: " + a;
  this.val = "val: " + b;
}
var obj = new proto("이름", "하보니");

document.write( obj.key ); // key: 이름
document.write( obj.val ); // val: 하보니
</script>

0 댓글