標籤:name xtend property fine 調用 簡潔 apply hive this
1、對象的繼承,一般的做法是複製:Object.extend
prototype.js的實現方式是:
Object.extend = function(destination,source){ //destination:目標 for(property in source){ //property:屬性 destination[property] = source[property]; } return destination; }
除此之外,還有種方法,就是Function.apply(當然使用Function.call也是可以的)
apply方法能劫持另外一個對象的方法,繼承另外一個對象的屬性
Function.apply(obj,args) 方法能接收兩個參數
obj:這個對象將代替Function類裡的this對象
args:這個是數組,它將作為參數傳給Function(args --> arguments)
apply示範代碼如下:
<script> function Person(name,age){ this.name = name; this.age = age; this.sayhello = function(){ alert(‘Hello‘) } } function Print(){ this.funcName = "Print"; this.show = function(){ var msg = [];//調用時:["name:tom","age:13","funcName:Print","grade:6","school:清華小學"] for (var key in this){ //調用時,this表示:Student,name:tom age:13 grade:6… if (typeof (this[key]) != "function") { msg.push([key,":",this[key]].join("")); //join("")把數組中的所有元素放入一個字串 } } console.log(msg.join(" ")); } } function Student(name,age,grade,school){ Person.apply(this,arguments);//this --> Student , arguments --> 0:"tom" 1:13 2:6 3:"清華小學" Print.apply(this,arguments); this.grade = grade; this.school = school; } var p1 = new Person("jake",10); p1.sayhello(); var s1 = new Student(‘tom‘,13,6,"清華小學"); s1.show(); s1.sayhello(); alert(s1.funcName);</script>
學生類不來不具備任何方法,但是在Person.apply(this,arguments)後,他就具備了Person類的sayhello方法和所有屬性。
在Print.apply(this,arguments)後就自動得到了show()方法
2、利用Apply的參數數組化來提高Function.apply()在提高程式效能方面的技巧
我們先從Math.max()函數說起,Math.max後面可以接任意個參數,最後返回所有參數中的最大值。比如:
alert(Math.max(5,8)); //8
alert(Math.max(5,7,9,3,1,6)); //9
但是在很多情況下,我們需要找出數組中最大的元素。
var arr = [5,7,9,1];
alert(Math.max(arr)); //這樣卻是不行的。一定要這樣寫
function getMax(arr){ var arrLen = arr.length; for(var i=0,ret = arr[0]; i<arrLen; i++){ ret = Math.max(ret,arr[i]); } return ret;}
這樣寫麻煩而且低效。如果用apply呢,看代碼:
<script> function getMax2(arr){ return Math.max.apply(null,arr); //arr --> 0:5 1:7 2:9 3:1 } var arr = [5,7,9,1]; console.log(getMax2(arr));</script>
兩端代碼達到了同樣的目的,但是getMax2缺優雅,高效,簡潔的多。
再比如數組的push方法。
var arr1 = [1,3,4];
var arr2 = [3,4,5];
如果我們要把arr2展開,然後一個個追加到arr1中去,最後讓arr1 = [1,3,4,3,4,5];
arr1.push(arr2)顯然不行的。因為這樣做會得到[1,3,4,[3,4,5]]
我們只能用一個迴圈去一個一個的push(當然也可以用arr1.concat(arr2)),但是concat方法並不改變arr1本身
var arrLen = arr2.length;for(var i=0; i<arrLen; i++){ arr1.push(arr2[i]); }
自從有了apply,事情就變得如此簡單
Array.prototype.push.apply(arr1,arr2);
轉自:http://www.cnblogs.com/delin/archive/2010/06/17/1759695.html#undefined
js中apply方法的使用