圖解call、apply、bind的異同及各種實戰應用演示
來自: http://www.cnblogs.com/shuiyi/p/5178742.html
一、圖解call、apply、bind的異同
JavaScript中函數可以通過3種方法改變自己的this指向,它們是call、apply、bind。它們3個非常相似,但是也有區別。下面表格可以很直觀看出三者的不同
方法 | 是否直接執行函數 | 傳入的參數 | 調用方式 |
call | 是 | (context,arg1,arg2,arg3...) 第二個參數之后都是實參 |
function.call(context,arg1,arg2,arg3...) |
apply | 是 | (context,[arg1,arg2,arg3...]) 第二個參數必須是數組 |
function.apply(context,[arg1,arg2,arg3...]) |
bind | 否 | (context) 只有一個參數 |
var newFunction = function.bind(context); newFunction(arg1,arg2,arg3...) |
二、實例:
1、call
var a = {x: 1}; var b = function (y, z) { console.log(this.x + y + z) }; b.call(a, 3, 4);//此時b的this(即b執行時的上下文)被改變為a,因此this.x為1,第二個參數之后都是傳給b實參。
2、apply
var a = {x: 1}; var b = function (arr) { console.log(this.x + arr[0] + arr[1]) }; b.call(a, [3, 4]);//此時b的this(即b執行時的上下文)被改變為a,第二個參數是一個數組
3、bind
var a = {x: 1}; var b = function (y, z) { console.log(this.x + y + z) }; var newB = b.bind(a);//此時b的this(即b執行時的上下文)被改變為a,由此生成一個新函數,函數不會立即執行。 newB(3, 4);//函數此時才執行
三、常用場景
1、數組之間追加
var array1 = [12, "foo", {name: "Joe"}, -2458]; var array2 = ["Doe", 555, 100]; Array.prototype.push.apply(array1, array2); / array1 值變為 [12 , "foo" , {name:"Joe"} , -2458 , "Doe" , 555 , 100] /View Code</pre>
2、獲取數組中的最大值和最小值
var numbers = [5, 458, 120, -215]; var maxInNumbers = Math.max.apply(Math, numbers); //458View Code</pre>
3、驗證是否是數組(前提是toString()方法沒有被重寫過)
function isArray(obj){ return Object.prototype.toString.call(obj) === '[object Array]'; }View Code</pre>
4、類(偽)數組使用數組方法
var domNodes = Array.prototype.slice.call(document.getElementsByTagName("*"));View Code</pre>
5、數字求和
function sum() { var numberSum = Array.prototype.reduce.apply(arguments, [function (prev, next) { return prev + next; }]); console.log(numberSum); } sum(1, 2, 3);View Code</pre>
備注:以上1-4的使用場景來自,有興趣的同學可以前往了解更多: https://github.com/chokcoco/apply-call-bind/tree/master
</div>
本文由用戶 hafe 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!