[召唤帖]召集JavaScript内置对象扩展原型函数,要求经典、原创、分不是问题。

KimSoft
博客专家认证
2006-03-11 05:32:56
加精
召集JavaScript内置对象扩展原型函数,要求经典、原创、分不是问题。我一个同事目前还有7000分的可用分。我将对比较好的原型函数集中整理后再发布到CSDN,希望各位高手不要藏私。

另:只要内置对象的原型(prototype)函数。
...全文
770 42 打赏 收藏 转发到动态 举报
写回复
用AI写文章
42 条回复
切换为时间正序
请发表友善的回复…
发表回复
KimSoft 2006-03-15
  • 打赏
  • 举报
回复
好多啊,谢谢楼上支持。
woyingjie 2006-03-14
  • 打赏
  • 举报
回复
mozilla 下没有的方法和属性~~

if (mozilla)
{
//////////////////////////////////////////////////////////////
/* HTMLObject.outerHTML || HTMLObject.innerText */

HTMLElement.prototype.__defineGetter__
(
"outerHTML",
function()
{
var str = "<" + this.tagName;

for (var i = 0; i < this.attributes.length; i++)
{
var attr = this.attributes[i];

str += " ";
str += attr.nodeName + "=" + '"' + attr.nodeValue + '"';
}

str += ">" + this.innerHTML + "</" + this.tagName + ">";

return str;
}
);

HTMLElement.prototype.__defineGetter__
(
"innerText",
function()
{
var rng = document.createRange();
rng.selectNode(this);

return rng.toString();
}
);

HTMLElement.prototype.__defineSetter__
(
"innerText",
function(txt)
{
var rng = document.createRange();
rng.selectNodeContents(this);
rng.deleteContents();
var newText = document.createTextNode(txt);
this.appendChild(newText);
}
);


/* event.srcElement || event.target */

Event.prototype.__defineGetter__
(
"srcElement",
function()
{
return this.target;
}
);

/* Object.attachEvent || Object.addEventListener
Object.detachEvent || Object.removeEventListener */

HTMLElement.prototype.attachEvent = Node.prototype.attachEvent = function(a, b)
{
return this.addEventListener(a.replace(/^on/i, ""), b,false);
};

HTMLElement.prototype.detachEvent = Node.prototype.detachEvent = function(a, b)
{
return this.removeEventListener(a.replace(/^on/i, ""), b, false);
};

/* XMLDocument.onreadystatechange, parseError
XMLDocument.createNode, load, loadXML,setProperty */

var _xmlDocPrototype = XMLDocument.prototype;

XMLDocument.prototype.__defineSetter__
(
"onreadystatechange",
function(f)
{
if (this._onreadystatechange)
{
this.removeEventListener("load", this._onreadystatechange, false);
}

this._onreadystatechange = f;

if (f)
{
this.addEventListener("load", f, false);
}

return f;
}
);

XMLDocument.prototype.createNode = function(aType, aName, aNamespace)
{
switch(aType)
{
case 1:
if (aNamespace && aNamespace != "")
{
return this.createElementNS(aNamespace, aName);
}
else
{
return this.createElement(aName);
}
case 2:
if (aNamespace && aNamespace != "")
{
return this.createAttributeNS(aNamespace,aName);
}
else
{
return this.createAttribute(aName);
}
case 3:
default:
return this.createTextNode("");
}
};

XMLDocument.prototype.__realLoad = _xmlDocPrototype.load;

XMLDocument.prototype.load = function(sUri)
{
this.readyState = 0;
this.__realLoad(sUri);
};

XMLDocument.prototype.loadXML = function(s)
{
var doc2 = (new DOMParser).parseFromString(s, "text/xml");

while (this.hasChildNodes())
{
this.removeChild(this.lastChild);
}

var cs=doc2.childNodes;
var l = cs.length;

for (var i = 0; i < l; i++)
{
this.appendChild(this.importNode(cs[i], true));
}
};

XMLDocument.prototype.setProperty = function(sName, sValue)
{
if (sName == "SelectionNamespaces")
{
this._selectionNamespaces = {};

var parts = sValue.split(/\s+/);
var re= /^xmlns\:([^=]+)\=((\"([^\"]*)\")|(\'([^\']*)\'))$/;

for (var i = 0; i < parts.length; i++)
{
re.test(parts[i]);
this._selectionNamespaces[RegExp.$1] = RegExp.$4 || RegExp.$6;
}
}
};

var _mozHasParseError = function(oDoc)
{
return !oDoc.documentElement || oDoc.documentElement.localName=="parsererror"
&& oDoc.documentElement.getAttribute("xmlns")=="http://www.mozilla.org/newlayout/xml/parsererror.xml";
};

XMLDocument.prototype.__defineGetter__
(
"parseError",
function()
{
var hasError = _mozHasParseError(this);

var res = {
errorCode : 0,
filepos : 0,
line : 0,
linepos : 0,
reason : "",
srcText : "",
url : ""
};

if (hasError)
{
res.errorCode = -1;

try
{
res.srcText = this.getElementsByTagName("sourcetext")[0].firstChild.data;
res.srcText = res.srcText.replace(/\n\-\^$/, "");
}
catch(ex)
{
res.srcText = "";
}

try
{
var s = this.documentElement.firstChild.data;
var re = /XML Parsing Error\:(.+)\nLocation\:(.+)\nLine Number(\d+)\,Column(\d+)/;
var a = re.exec(s);
res.reason = a[1];
res.url = a[2];
res.line = a[3];
res.linepos = a[4];
}
catch(ex)
{
res.reason="Unknown";
}
}

return res;
}
);


/* Attr.xml */

Attr.prototype.__defineGetter__
(
"xml",
function()
{
var nv = (new XMLSerializer).serializeToString(this);

return this.nodeName + "=\""+nv.replace(/\"/g,""")+"\"";
}
);


/* Node.xml, text, baseName
Node.selectNodes, selectSingleNode, transformNode, transformNodeToObject */

Node.prototype.__defineGetter__
(
"xml",
function()
{
return (new XMLSerializer).serializeToString(this);
}
);

Node.prototype.__defineGetter__
(
"text",
function()
{
var cs = this.childNodes;
var l = cs.length;
var sb = new Array(l);

for (var i = 0; i < l; i++)
{
sb[i] = cs[i].text.replace(/^\n/, "");
}

return sb.join("");
}
);

Node.prototype.__defineGetter__
(
"baseName",
function()
{
var lParts = this.nodeName.split(":");

return lParts[lParts.length-1];
}
);


Node.prototype.selectNodes = function(sExpr)
{
var doc = this.nodeType==9 ? this : this.ownerDocument;
var nsRes = doc.createNSResolver(this.nodeType==9 ? this.documentElement : this);
var nsRes2;

if (doc._selectionNamespaces)
{
nsRes2 = function(s)
{
if (s in doc._selectionNamespaces)
{
return doc._selectionNamespaces[s];
}

return nsRes.lookupNamespaceURI(s);
};
}
else
{
nsRes2=nsRes;
}

var xpRes = doc.evaluate(sExpr, this, nsRes2, 5, null);
var res=[];
var item;

while ((item = xpRes.iterateNext()))
res.push(item);

return res;
};


Node.prototype.selectSingleNode = function(sExpr)
{
var doc = this.nodeType==9 ? this : this.ownerDocument;
var nsRes = doc.createNSResolver(this.nodeType==9 ? this.documentElement : this);
var nsRes2;

if(doc._selectionNamespaces)
{
nsRes2 = function(s)
{
if(s in doc._selectionNamespaces)
{
return doc._selectionNamespaces[s];
}

return nsRes.lookupNamespaceURI(s);
};
}
else
{
nsRes2=nsRes;
}

var xpRes = doc.evaluate(sExpr, this, nsRes2, 9, null);

return xpRes.singleNodeValue;
};

Node.prototype.transformNode = function(oXsltNode)
{
var doc = this.nodeType==9 ? this : this.ownerDocument;
var processor = new XSLTProcessor();
processor.importStylesheet(oXsltNode);
var df = processor.transformToFragment(this, doc);

return df.xml;
};

Node.prototype.transformNodeToObject = function(oXsltNode, oOutputDocument)
{
var doc = this.nodeType==9 ? this : this.ownerDocument;
var outDoc = oOutputDocument.nodeType==9 ? oOutputDocument : oOutputDocument.ownerDocument;
var processor=new XSLTProcessor();
processor.importStylesheet(oXsltNode);
var df=processor.transformToFragment(this,doc);

while (oOutputDocument.hasChildNodes())
{
oOutputDocument.removeChild(oOutputDocument.lastChild);
}

var cs=df.childNodes;
var l=cs.length;

for(var i=0; i<l; i++)
{
oOutputDocument.appendChild(outDoc.importNode(cs[i],true));
}
};


/* TextNode.text */

Text.prototype.__defineGetter__
(
"text",
function()
{
return this.nodeValue;
}
);

//////////////////////////////////////////////////////////////
}
woyingjie 2006-03-14
  • 打赏
  • 举报
回复
/* Function.call & applay 兼容ie5 参考prototype.js */

if (!Function.prototype.apply)
{
Function.prototype.apply = function(object, argu)
{
if (!object)
{
object = window;
}

if (!argu)
{
argu = new Array();
}

object.__apply__ = this;

var result = eval("object.__apply__(" + argu.join(", ") + ")");
object.__apply__ = null;

return result;
};

Function.prototype.call = function(object)
{
var argu = new Array();

for (var i = 1; i < arguments.length; i++)
{
argu[i-1] = arguments[i];
}

return this.apply(object, argu)
};
}


/* 为类蹭加set & get 方法, 参考bindows */

Function.READ = 1;
Function.WRITE = 2;
Function.READ_WRITE = 3;

Function.prototype.addProperty = function(sName, nReadWrite)
{

nReadWrite = nReadWrite || Function.READ_WRITE;

var capitalized = sName.charAt(0).toUpperCase() + sName.substr(1);

if (nReadWrite & Function.READ)
{
this.prototype["get"+capitalized] = new Function("","return this._" + sName + ";");
}

if (nReadWrite & Function.WRITE)
{
this.prototype["set"+capitalized] = new Function(sName,"this._" + sName + " = " + sName + ";");
}
};


/* 类继承, 参考bindows继承实现方式 */

Function.prototype.Extend = function(parentFunc, className)
{
var _parentFunc = parentFunc;

var p = this.prototype = new _parentFunc();

p.constructor = this;

if (className)
{
p._className = className;
}
else
{
p._className = "Object";
}

p.toString = function()
{
return "[object " + this._className + "]";
};

return p;
};


/* 实体化类 */

Function.prototype.Create = function()
{
return new this;
};
woyingjie 2006-03-14
  • 打赏
  • 举报
回复
/******************************************************************************
* Array
******************************************************************************/

/* 返回数组中最大值 */
Array.prototype.max = function()
{
var i, max = this[0];

for (i = 1; i < this.length; i++)
{
if (max < this[i])
{
max = this[i];
}
}

return max;
};

/* 兼容ie5.0 */
if (!Array.prototype.push)
{
Array.prototype.push = function()
{
var startLength = this.length;

for (var i = 0; i < arguments.length; i++)
{
this[startLength + i] = arguments;
}

return this.length;
};
}

/* 返回 Array 对象内第一次出现 给定值 的索引值 */
if (!Array.prototype.indexOf)
{
Array.prototype.indexOf = function(obj, fromIndex)
{
if (fromIndex == null)
{
fromIndex = 0;
}
else if (fromIndex < 0)
{
fromIndex = Math.max(0, this.length + fromIndex);
}

for (var i = fromIndex; i < this.length; i++)
{
if (this[i] === obj)
{
return i;
}
}

return-1;
};
}

/* 返回 Array 对象内最后一次出现 给定值 的索引值 */
if (!Array.prototype.lastIndexOf)
{
Array.prototype.lastIndexOf = function(obj, fromIndex)
{
if (fromIndex == null)
{
fromIndex = this.length - 1;
}
else if (fromIndex < 0)
{
fromIndex=Math.max(0, this.length+fromIndex);
}

for (var i = fromIndex; i >= 0; i--)
{
if (this[i] === obj)
{
return i;
}
}

return -1;
};
}

/* Array.insert(值, 索引) */
Array.prototype.insertAt = function(o, i)
{
this.splice(i, 0, o);
};

/* Array.insertBefore(插入值, 值) */
Array.prototype.insertBefore = function(o, o2)
{
var i = this.indexOf(o2);

if (i == -1)
{
this.push(o);
}
else
{
this.splice(i, 0, o);
}
};

/* 删除给定元素 */
Array.prototype.remove = function(o)
{
var i = this.indexOf(o);

if (i != -1)
{
this.splice(i, 1);
}
};

/* 删除给定索引值位置的元素 */
Array.prototype.removeAt = function(i)
{
this.splice(i, 1);
};

/* 判断是否存在给定值 */
Array.prototype.contains = function(o)
{
return this.indexOf(o) != -1
};

/* 随机排序 */
Array.prototype.random = function ()
{
return this.sort(function(){return Math.random()*new Date%3-1})
};

/* 是否包含给定数组 */
Array.prototype.compare = function (a)
{
return this.toString().match(new RegExp("("+a.join("|")+")", "g"))
};

/* 复制数组 */
Array.prototype.copy = function(o)
{
return this.concat();
};

/* */
if (!Array.prototype.forEach)
{
Array.prototype.forEach = function(f, obj)
{
var l = this.length;

for (var i = 0; i < l; i++)
{
f.call(obj, this[i], i, this);
}
};
}

/* */
if (!Array.prototype.filter)
{
Array.prototype.filter = function(f, obj)
{
var l = this.length;
var res = [];

for (var i = 0; i < l; i++)
{
if (f.call(obj, this[i], i, this))
{
res.push(this[i]);
}
}

return res;
};
}

/* */
if (!Array.prototype.map)
{
Array.prototype.map = function(f, obj)
{
var l = this.length;
var res = [];

for (var i = 0; i < l; i++)
{
res.push(f.call(obj, this[i], i, this));
}

return res;
};
}

/* */
if (!Array.prototype.some)
{
Array.prototype.some = function(f, obj)
{
var l = this.length;

for (var i = 0; i < l; i++)
{
if (f.call(obj, this[i], i, this))
{
return true;
}
}

return false;
};
}

/* */
if (!Array.prototype.every)
{
Array.prototype.every = function(f, obj)
{
var l = this.length;

for (var i = 0; i < l; i++)
{
if (!f.call(obj, this[i], i, this))
{
return false;
}
}

return true;
};
}


/******************************************************************************
* Date
******************************************************************************/

/* 格式化日期yyyy-MM-dd-mm-ss-q-S */
Date.prototype.Format = function(format)
{
var o = {
"M+" : this.getMonth()+1,
"d+" : this.getDate(),
"h+" : this.getHours(),
"m+" : this.getMinutes(),
"s+" : this.getSeconds(),
"q+" : Math.floor((this.getMonth()+3)/3),
"S" : this.getMilliseconds()
};

if (/(y+)/.test(format))
{
format = format.replace(RegExp.$1, (this.getFullYear()+"").substr(4 - RegExp.$1.length));
}

for (var k in o)
{
if (new RegExp("("+ k +")").test(format))
{
format = format.replace(RegExp.$1, RegExp.$1.length==1 ? o[k] :
("00"+ o[k]).substr((""+ o[k]).length));
}
}

return format;
};

/* 是否周末 */
Date.prototype.isWeekend = function()
{
return (this.getDay() % 6) ? false : true;
};

/* 该月总共天数 */
Date.prototype.getMDate = function()
{
return (new Date(this.getFullYear(), this.getMonth()+1, 0).getDate())
};


/******************************************************************************
* Math
******************************************************************************/

/* Math.random()的重载函数 ; Math.random(n),返回小于n的整数 ; */

var _rnd = Math.random;

Math.random = function(n)
{
if (n == undefined)
{
return _rnd();
}
else if (n.toString().match(/^\-?\d*$/g))
{
return Math.round(_rnd()*n);
}
else
{
return null;
}
};


/******************************************************************************
* Number
******************************************************************************/

/* 返回数值的长度 */
Number.prototype.length = function()
{
return this.toString().length;
};

/* 将整数形式RGB颜色值转换为HEX形式 */
Number.prototype.toColorPart = function()
{
var digits = this.toString(16);

if (this < 16)
{
return '0' + digits;
}

return digits;
};

/* 返回000888形式 */
Number.prototype.format = function(n)
{
if (this.length() >= n)
{
return this;
}

return ((new Array(n).join("0")+(this|0)).slice(-n));
};


/******************************************************************************
* String
******************************************************************************/

/* 去掉字符串左端空格 */
String.prototype.lTrim = function()
{
return this.replace(/^\s*/, "");
};

/* 去掉字符串右端空格 */
String.prototype.rTrim = function()
{
return this.replace(/\s*$/, "");
};

/* 去掉字符串两端空格 */
String.prototype.Trim = function()
{
return this.replace(/^\s*|\s*$/g, "");
};

/* 返回字符串字节数 */
String.prototype.getBytesLength = function()
{
return this.replace(/[^\x00-\xff]/g,"**").length;
};

/* 字符串首字母大写 */
String.prototype.capitalize = function()
{
return this.charAt(0).toUpperCase()+this.substr(1);
};
yunlaiyunqu 2006-03-14
  • 打赏
  • 举报
回复
up ^_^
mingxuan3000 2006-03-14
  • 打赏
  • 举报
回复
这个应该置顶
iuhxq 2006-03-13
  • 打赏
  • 举报
回复
佩服各位高手的JS功力,象你们学习
创造奇迹9999 2006-03-13
  • 打赏
  • 举报
回复
先收藏下
ttyp 2006-03-13
  • 打赏
  • 举报
回复
呵呵,被挖走了

正则用处可大了,有时候能起到事半功倍的效果,.net里的正则比JS的还复杂
KimSoft 2006-03-13
  • 打赏
  • 举报
回复
一看正则式就头大。一直将这个章节跳过去的,不知有没好的学习方法。
hbhbhbhbhb1021 2006-03-13
  • 打赏
  • 举报
回复
TO meizz(梅花雪)
灯泡(这个是帖图),以后我写代码要多注意了。
meizz 2006-03-13
  • 打赏
  • 举报
回复
还有就是不要在正则里动不动就添加 g 模式:
/^([\u4E00-\u9FA5])*$/g //String.prototype.isAllChinese
这句正则里的 g 模式若是配合以 m 模式那还说得过去,你即然没有 m 那何必要添个 g ?
还有你用的是 * 若这一个空字符串你也认为是 isAllChinese ?所以应该用+
/^[\u4e00-\u9fa5\uf900-\ufa2d]+$/

var pattern = /[\u4E00-\u9FA5]/g; //String.prototype.isContainChinese
这句正则里加了一个无用的 g ,对系统消耗则相差甚大呀
KimSoft 2006-03-13
  • 打赏
  • 举报
回复
楼上两位再帮我看看这个帖子。。。

http://community.csdn.net/Expert/topic/4609/4609496.xml?temp=.1486322
meizz 2006-03-13
  • 打赏
  • 举报
回复
减少消耗(少用了变量)
提高效率(少了if判断)
代码精简
hbhbhbhbhb1021 2006-03-13
  • 打赏
  • 举报
回复
的确,我的代码多用到变量
就拿这里来讲,这里有两句return true; return false;
我想这里就需要有两个对象来存储,浪费了资源。
而meizz的不管返回true或者false都应该存储在一个对象里。
TO meizz
除了这点之外,写成那种还有其他原因吗?
dh20156 2006-03-13
  • 打赏
  • 举报
回复
支持,学习 ^_^
meizz 2006-03-13
  • 打赏
  • 举报
回复
优化一下代码:
String.prototype.isContainChinese = function()
{
var pattern = /[\u4E00-\u9FA5]/g;
if (pattern.test(this))
return true;
else
return false;
}

==>

String.prototype.isContainChinese = function()
{
return /[\u4e00-\u9fa5\uf900-\ufa2d]/.test(this);
}

其它的类推优化
LCKKING 2006-03-13
  • 打赏
  • 举报
回复
强啊,学习!
hbhbhbhbhb1021 2006-03-13
  • 打赏
  • 举报
回复
嘿嘿,大家都来给KimSoft(革命的小酒天天醉) 捧场啊
hbhbhbhbhb1021 2006-03-13
  • 打赏
  • 举报
回复
工作日
Date.prototype.isWorkDay=function()
{
var year=this.getYear();
var month=this.getMonth();
var date=this.getDate();
var hour=this.getHours();
if(this.getDay()==6)
{
return false
}
if(this.getDay()==7)
{
return false
}
if((hour>7)&&(hour<17))
{
return true;
}
else
{
return false
}
}

var a=new Date();
alert(a.isWorkDay());

是否全为汉字
String.prototype.isAllChinese = function()
{
var pattern = /^([\u4E00-\u9FA5])*$/g;
if (pattern.test(this))
return true;
else
return false;
}


包含汉字

String.prototype.isContainChinese = function()
{
var pattern = /[\u4E00-\u9FA5]/g;
if (pattern.test(this))
return true;
else
return false;
}

全角转半角

<script language=javascript>
String.prototype.DBC2SBC=function()
{

var result = '';
for(var i=0;i<str.length;i++){
code = str.charCodeAt(i);//获取当前字符的unicode编码
if (code >= 65281 && code <= 65373)//在这个unicode编码范围中的是所有的英文字母已经各种字符
{
result += String.fromCharCode(str.charCodeAt(i) - 65248);//把全角字符的unicode编码转换为对应半角字符的unicode码
}else if (code == 12288)//空格
{
result += String.fromCharCode(str.charCodeAt(i) - 12288 + 32);
}else
{
result += str.charAt(i);
}
}
return result;
}
var str="FSDFSDG广泛豆腐干"
alert(str)
alert(str.DBC2SBC())
</script>
加载更多回复(22)

87,914

社区成员

发帖
与我相关
我的任务
社区描述
Web 开发 JavaScript
社区管理员
  • JavaScript
  • 无·法
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧