網上大牛,說的很直接,劫持另外一個對象(a)的方法,繼承a的屬性., 我個人理解,就是把你的變成我的.
1.對象的繼承,一般的做法是複製:Object.extend
下面是prototype.js的實現方式是:傳入兩個對象,把source裏的屬性,放到destination裏,很直白
Object.extend = function(destination, source) { for (var property in source) { destination[property] = source[property]; } return destination; }
2.Function.apply(obj, args)的實現
當然還有要說的apply()方法,就是:
Function.apply(obj,args)方法,需要接收兩個參數.
- obj: 這個對象將代替Function類裏this對象
- args: 這個是數組,它將作爲參數傳給Function(args-->arguments)
下面測試使用apply方法,實現學生對象,擁有'人'對象的喫的功能以及寫的功能.
有一個我總用的在線測試js的工具, 直接在上面測試就行,https://jsrun.net/new
function Person(name,age){//定一個人的對象,有名字,年齡 this.name = name; this.age = age; //還有喫的功能 this.eat=function(){ console.log('喫'); } } function Write(){//寫字的類 this.funcName = "Write"; this.show = function(){ let msg = []; for(let key in this){ if(typeof(this[key]) != "function"){ msg.push([key, ":", this[key]].join("")); } } console.log(msg.join(" ")); } } function Student(name,age,grade,school){ //學生類 Person.apply(this,arguments); Write.apply(this,arguments); this.grade=grade; //年級 this.school=school; //學校 } let p1 = new Person('Mark',23); p1.eat(); let s1 = new Student('Jhon',23,3,"鐵路大學"); s1.show(); s1.eat();
結果展示:
> "喫" > "name:Jhon age:23 funcName:Write grade:3 school:鐵路大學" > "喫"
結論: 學生類本來不具備任何方法,但是在Person.apply(this,arguments)後,他就具備了Person類的eat()方法和所有屬性。apply方法劫持另外一個對象的方法,繼承另外一個對象的屬性
2.apply()的應用
Function.apply()在提升程序性能方面的技巧
我們先從Math.max()函數說起,Math.max後面可以接任意個參數,最後返回所有參數中的最大值。
比如
alert(Math.max(5,8)) //8
alert(Math.max(5,7,9,3,1,6)) //9
但是在很多情況下,我們需要找出數組中最大的元素。
例如:
let arr = [1,2,0,4]; //max方法不支持數組格式,需要遍歷 const getMax1 = function(arr){ var back = ''; for(var i = 0,back = arr[0]; i < arr.length; i++){ back = Math.max(arr[i],back); } return back; } console.log(getMax1(arr));
上述,我們需要得到數組中最大的元素,需要遍歷,在調用max方法找到最大方法,如果使用apply()方法,可以很簡潔的獲取最大值
//使用apply之後, const getMax = function(arr){ return Math.max.apply(null,arr); } console.log(getMax(arr));
兩段代碼可以看出,使用apply(),代碼簡潔,高效。根據自己實際情況,靈活使用apply()方法.