javascript的封装实例
Posted 快乐地编程
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了javascript的封装实例相关的知识,希望对你有一定的参考价值。
StringBuffer方法的js自定义封装:
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="Generator" content="EditPlus®">
<meta name="Author" content="">
<meta name="Keywords" content="">
<meta name="Description" content="">
<title>Document</title>
</head>
<body>
<script language="javascript">
function StringBuffer()
{
this._strings_=new Array();
}
StringBuffer.prototype.append=function(str)
{
this._strings_.push(str);
}
StringBuffer.prototype.toString=function(){
return this._strings_.join("");
}
//call
var strobj=new StringBuffer();
strobj.append("hello");
strobj.append("world");
alert(strobj.toString());
</script>
</body>
</html>
修改对象已有的属性,创建新方法
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="Generator" content="EditPlus®">
<meta name="Author" content="">
<meta name="Keywords" content="">
<meta name="Description" content="">
<title>Document</title>
</head>
<body>
<script language="JavaScript">
Number.prototype.toHexString=function()
{
return this.toString(16);
}
//call
var iNum=15;
alert(iNum.toHexString());
</script>
</body>
</html>
封装Array的压栈和出栈及indexOf方法:
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="Generator" content="EditPlus®">
<meta name="Author" content="">
<meta name="Keywords" content="">
<meta name="Description" content="">
<title>Document</title>
</head>
<body>
<script language="JavaScript">
Array.prototype.enqueue=function(vItem)
{
this.push(vItem);
}
Array.prototype.dequeue=function() {
return this.shift();
}
Array.prototype.indexOf=function(vItem)
{
for(var i=0;i<this.length;i++)
{
if(vItem==this[i])
{
return i;
}
}
return -1;
}
//call
var arr=new Array();
arr.enqueue("aaa");
arr.enqueue("bbb");
arr.dequeue();
alert(arr);
</script>
</body>
</html>
封装Object的alert方法:
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="Generator" content="EditPlus®">
<meta name="Author" content="">
<meta name="Keywords" content="">
<meta name="Description" content="">
<title>Document</title>
</head>
<body>
<script language="JavaScript">
Object.prototype.alert=function()
{
alert(this.valueOf());
}
//call
var str="hello";
var iNum=33;
str.alert();
iNum.alert();
</script>
</body>
</html>
以上是关于javascript的封装实例的主要内容,如果未能解决你的问题,请参考以下文章
编写自己的代码库(javascript常用实例的实现与封装)