码迷,mamicode.com
首页 > 编程语言 > 详细

javascript的封装实例

时间:2016-03-20 00:19:54      阅读:179      评论:0      收藏:0      [点我收藏+]

标签:

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的封装实例

标签:

原文地址:http://www.cnblogs.com/klsw/p/5296646.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!