用原型函數(prototype)可以定義一些很方便的自訂函數,實現各種自訂功能。
Javascript 中的原型函數(prototype)的工作原理,在 javascript 中每次聲明新函數的過程中,就會為其建立一個 prototype 的屬性。在未加其他附帶條件情況下,所有的 prototype 屬性都會自動擷取 constractor 屬性,constructor 內包含一個指向 prototype 屬性所屬函數的指標(就是說 constructor 回指建構函式本身)。
舉個例子來說,Fruit.prototype.constructor 指向 Fruit。並且可以通過這個建構函式,為其添加更多的屬性和方法。
當調用建構函式建立一個新執行個體後,該執行個體內部包含一個指標指向建構函式的原型函數。此時我們不用去關心內部的這個指標到底是什麼(這個指標還的確有個名字:__proto__ 估計是為了對應 prototype 而起的名字吧 ~\(≧▽≦)/~ ),只需記住它的指向即可(指向建構函式的原型函數)。需要注意的是,這個 __proto__ 只存在於函數執行個體與建構函式的原型函數之間,而非執行個體與建構函式之間。
下面是使用 prototype 自訂了3個函數,分別是去掉數組中的重複值,還有求數組中的最大值與最小值。
數組定義為: var arr = [2,1,3,2,1,4,3,4,2,1];
程式碼為:
<script type="text/javascript">Array.prototype.unique = function(){ var a = {}; var len = this.length; for(var i=0; i < len; i++) { if(typeof a[this[i]] == "undefined") a[this[i]] = 1; } this.length = 0; for(var i in a) this[this.length] = i; return this; } Array.prototype.max = function(){ //最大值 return Math.max.apply({},this) }Array.prototype.min = function(){ //最小值 return Math.min.apply({},this) }var arr = [2,1,3,2,1,4,3,4,2,1];var btn1 = document.getElementById("btn1");btn1.onclick = function(){arr.unique();alert(arr.toString());}var btn2 = document.getElementById("btn2");btn2.onclick = function(){alert(arr.max());}var btn3 = document.getElementById("btn3");btn3.onclick = function(){alert(arr.min());}</script>