javascript

자바 스크립트 내장 객체 오버라이딩 (javascript prototype overriding)

jeeyong 2007. 11. 12. 08:25

String.prototype.myComment;
String.prototype.getLength = function(){ return this.length; }
String
.prototype.toString    = function(){ return "김덕배님의 말 : " + this.valueOf(); }

var o = new String("Hello My Girl");
o.myComment = "This is Object";

alert( o.myComment ); //"This is Object"
alert( o.getLength() ); //13
alert( o ); //"김덕배님의 말 : Hello My Girl"

1. String 객체의 getLength()와 toString()를 오버라이팅 한다.(이러한 방법으로 자바스크립메소드의 오버라이딩이 가능하다. 내장 객체를 오버라이딩 할경우 키워드prototype을 사용해야한다.

2. 위의 소스를 보면 String (o.myComment = "This is Object"; ) 객체를 생성한 후 스트링 객체에 다른 스트링 객체를 넣은 것을 볼 수 있다.