<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>修改对象</title>
</head>
<body>
1.创建新方法:可以用prototype属性为任何已有的类定义新方法,就像处理自己的类一样(类似C#里的扩展方法)。<br />
<script type="text/javascript">
//实例1:数字按十六进制输出
Number.prototype.toHexString = function () {
return this.toString(16);
}
//调用
var num = 15;
alert("实例1:数字按十六进制输出:" + num.toHexString());
//实例2:数组索引
Array.prototype.indexOf = function (item) {
for (var i = 0; i < this.length; i++) {
if (item == this[i]) {
return i;
}
}
}
//调用
var colorArr = new Array("red", "green", "yellow");
alert("实例2:数组索引:" + colorArr.indexOf("green"));
//实例3:扩展Object类方法
Object.prototype.showValue = function () {
return this.valueOf();
}
//调用
var colors = new Array("red", "green", "yellow");
var str = "hello";
alert("实例3:扩展Object类方法:" + str.showValue());
alert("实例3:扩展Object类方法:" + colors.showValue());
</script>
</body>
</html>