1、對象的繼承,一般的做法是復制:Object.extend
prototype.js的實現方式是:
Object.extend = function(destination, source) {
for (property in source) {
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=[];
for(var key in this){
if(typeof(this[key])!="function"){
msg.push([key,":",this[key]].join(""));
}
}
alert(msg.join(" "));
};
}
function Student(name,age,grade,school){ //學生類
Person.apply(this,arguments);
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呢,看代碼:
function getMax2(arr){
return Math.max.apply(null,arr);
}
兩段代碼達到了同樣的目的,但是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)