js中的call()與apply()

來源:互聯網
上載者:User

標籤:style   blog   color   io   ar   strong   sp   div   on   

js中的call()函數和apply()函數:

1、主要作用:是用於指定範圍和傳參

(1)用於指定範圍 

 1  window.color = "red"; 2  var o = { color: "blue" }; 3  var sayColor = function () { 4  debugger; 5  alert(this.color); 6   } 7  sayColor(); 8  9  sayColor.apply(this);//undefinded10  sayColor.apply(window);//red11  sayColor.apply(o);//blue

(2)用於傳參

 1   that = this; 2   var sum = function (n1, n2) { 3   debugger; 4   this.n1 = n1; 5   this.n2 = n2; 6   return this.n1 + this.n2; 7 } 8   var applySum1 = function (n1, n2) { 9   that.aaaaa = function () { };10   return sum.apply(that, arguments); ///that都是windown11 }12   var applySum2 = function (n1, n2) {13   that.bbbbb = function () { };14   return sum.apply(that, [n1, n2]); ///that都是windown15 }16   var callSum = function (n1, n2) {17   that.ccccc = function () { };18   return sum.call(that, n1, n2); ///that都是windown19 }20 alert(applySum1(10, 12)); //2221 alert(applySum2(10, 13)); //2322 alert(callSum(14, 10)); //24    

2、apply()與call()解析

  apply:方法能劫持另外一個對象的方法,繼承另外一個對象的屬性.

 Function.apply(obj,args)方法能接收兩個參數
obj:這個對象將代替Function類裡this對象
args:這個是數組,它將作為參數傳給Function(args-->arguments)

         call:和apply的意思一樣,只不過是參數列表不一樣.

  Function.call(obj,n1,n1,...);

3、apply()巧用

(1)Math.max 可以實現得到數組中最大的一項

因為Math.max 參數裡面不支援Math.max([param1,param2]) 也就是數組

但是它支援Math.max(param1,param2,param3…),所以可以根據剛才apply的那個特點來解決 var max=Math.max.apply(null,array),這樣輕易的可以得到一個數組中最大的一項(apply會將一個數組裝換為一個參數接一個參數的傳遞給方法)

 這塊在調用的時候第一個參數給了一個null,這個是因為沒有對象去調用這個方法,我只需要用這個方法幫我運算,得到返回的結果就行,.所以直接傳遞了一個null過去。

1  var arg = [5, 2, 1, 6, 8];2  var max = Math.max.apply(null, arg);3  var min = Math.min.apply(null, arg);4  alert("max:" + max + "---min:" + min);

結果:max:8---min:1

(2)Math.min  可以實現得到數組中最小的一項

同樣和 max是一個思想 var min=Math.min.apply(null,array);

(3)可以將兩個數組合并

1  var ar1 = [1, 2, 5];2  var ar2 = [5, 7, 9];3  ar1.push.apply(ar1, ar2);//ar1=[1,2,5,5,7,9]

而ar1.push(ar2);//結果ar1=[1,2,5,[5,7,9]]

 

js中的call()與apply()

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.