本文實例講述了Javascript中prototype屬性實現給內置對象添加新的方法。分享給大家供大家參考。具體實現方法如下:
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>prototype屬性使用(給內置對象添加新的方法,方便調用)</title>
<script type="text/javascript">
function getMaxFunc() {
var max = this[0];
for (var i in this) {
if (max < this[i]) {
max = this[i];
}
}
return max;
}
Array.prototype.getMax = getMaxFunc;
//Array是Javascript的內置對象,這里使用prototype定義一個新的方法getMax
var myArr = [3, 5, 6, 7, 9];
var max = myArr.getMax();
//這里就可以直接使用myArr.getMax了,像使用內置對象的方法一樣使用
alert("max=" + max);
</script>
</head>
<body>
</body>
</html>
希望本文所述對大家的javascript程序設計有所幫助。
新聞熱點
疑難解答