主要參考
Function.prototype.bind()
-
語法:
fun.bind(thisArg[, arg1[, arg2[, ...]) -
描述:
創建一個與被調函數具有相同函數體的新函數(綁定函數)
- 新函數的 this 綁定到 bind() 的第一個參數 thisArg;
- bind() 也接受將預設參數 arg1、arg2、... 提供給原函數
應用示例:配合 setTimeout
-
場景描述:
點擊按鈕,通過綁定的 this 對象控制按鈕等待狀態,並延遲 2s 后修改當前按鈕字面值為新獲取到的參數列表
-
代碼示例:
var button = document.getElementById('BIND_FUNCTION'); button.addEventListener('tap', function() { mui(this).button('loading'); setTimeout(function() { mui(this).button('reset'); mui(this)[0].innerText = Array.prototype.slice.call(arguments); }.bind(this, 50, 100, 200), 2000); });
預設參數將插入到目標函數的參數列表開始位置
-
代碼示例:
function list() { return Array.prototype.slice.call(arguments); } var list1 = list(1, 2, 3); // [1, 2, 3] // 創建一個list的綁定函數newList,並插入一個預設參數37 var newList = list.bind(undefined, 37); var list2 = newList(1, 2, 3); // [37, 1, 2, 3]
