标签:javascript 面向对象编程 prototype js
接上一讲,prototype可以用于动态增强对象,那么有些js的原生类,没有提供我们想要的功能的时候,我们就可以用prototype对其增强。
下面是一些具体的案例,希望大家能举一反三:
<pre name="code" class="javascript">//检测指定元素是否在数组中
Array.prototype.contains=function(e){
for(i in this){
if(this[i]===e)
return true;
}
return false;
};
//测一测
alert(new Array('a','b').contains('a'));
var arr = ['red','yellow','blue'];
alert(arr.contains('red'));//头尾去空
String.prototype.trim=function(){
return this.replace(/^\s+|\s+$/igm,'');
};
alert("' abc '的长度==="+' abc '.length);
//测一测去空后的长度
alert("' abc '去空后的长度==="+' abc '.trim().length);JavaScript面向对象编程(4)prototype使用案例:内置对象增强
标签:javascript 面向对象编程 prototype js
原文地址:http://blog.csdn.net/zhengwei223/article/details/41779003