標籤:
一、圖解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
2、擷取數組中的最大值和最小值
var numbers = [5, 458, 120, -215]; var maxInNumbers = Math.max.apply(Math, numbers); //458
View Code
3、驗證是否是數組(前提是toString()方法沒有被重寫過)
function isArray(obj){ return Object.prototype.toString.call(obj) === ‘[object Array]‘; }View Code
4、類(偽)數組使用數組方法
var domNodes = Array.prototype.slice.call(document.getElementsByTagName("*"));View Code
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
備忘:以上1-4的使用情境來自,有興趣的同學可以前往瞭解更多:https://github.com/chokcoco/apply-call-bind/tree/master
圖解call、apply、bind的異同及各種實戰應用示範