你的位置:首页 > Java教程

[Java教程]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>