Posted on 2008. 1. 23. 10:34
Filed Under Javascript

prototype 속성은 객체에 새로운 속성이나 메소드를 추가할때 사용된다.

※ 속성추가시
아래와 같은 내용이 있다.
<script language="javascript">
<!--
   test = new Array(3);
   Array.prototype.comment = null;
   test.comment = "Array 객체에 추가한 속성";
   document.write(test.comment);
-->
</script>
test 라는 배열에 comment라는 새로운 속성을 추가하고 값을 할당하는 내용이다.


※ 메소스 추가시
<script language="javscript">
<!--
   function array_max() {
      var i, max = this[0];
      for(i=1; i<this.length; i++) {
         if(max < this[i]) max = this[i];
      }
      return max;
   }

   Array.prototype.max = array_max;
   var x = new Array(1,2,3,4,5);
   document.write(x.max());
-->
</script>





※ 아래는 행복한고니님의 string prototype 사용예이다.
[출처] http://www.phpschool.com/gnuboard4/bbs/board.php?bo_table=tipntech&wr_id=31309

자바스크립트용으로 PHP의 함수들을 흉내내본 것입니다.
더 필요한 게 있으면 그때그때 추가할 예정입니다.
기능 건의 받습니다. -_- v

prototype 으로 정의되어있어서...

("<b>test</b>").stripTags();

혹은

var str = " !!!! ";
str = str.trim();

과 같이 사용가능합니다.

---------------------
// HTML 특수문자를 변환
String.prototype.htmlChars = function () {
var str = ((this.replace('"', '&amp;')).replace('"', '&quot;')).replace('\'', '&#39;');
return (str.replace('<', '&lt;')).replace('>', '&gt;');
}

// 좌우 공백없애는 함수
String.prototype.trim = function () { return this.replace(/(^s*)|(s*$)/g, ""); }

// 왼쪽 공백없애는 함수
String.prototype.ltrim = function () { return this.replace(/^s*/g, ""); }

// 오른쪽 공백없애는 함수
String.prototype.rtrim = function () { return this.replace(/s*$/g, ""); }

// 태그만 제거
String.prototype.stripTags = function () {
var str = this;
var pos1 = str.indexOf('<');

if (pos1 == -1) return str;
else {
var pos2 = str.indexOf('>', pos1);
if (pos2 == -1) return str;
return (str.substr(0, pos1) + str.substr(pos2+1)).stripTags();
}
}

// 대소문자 구별하지 않고 단어 위치 찾기
String.prototype.ipos = function (needle, offset) {
var offset = (typeof offset == "number")?offset:0;
return str.toLowerCase().indexOf(needle.toLowerCase(), offset);
}

// 대소문자 구별하지 않고 뒤에서부터 단어위치 찾기
String.prototype.ripos = function (needle, offset) {
var offset = (typeof offset == "number")?offset:0;
return str.toLowerCase().lastIndexOf(needle.toLowerCase(), offset);
}

// 문자열을 배열로
String.prototype.toArray = function () {
var len = this.length;
var arr = new Array;
for (var i=0; i<len; i++) arr[i] = this.charAt(i);
return arr;
}
---------------------

About

by 청지인

Notice

Counter

· Total
:
· Today
:
· Yesterday
: