JavaScript - 向回调函数中传递(绑定)this及其他参数



主要参考


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]    
    

posted @ 2018-08-02 15:45  JustKidding  阅读(2430)  评论(0编辑  收藏  举报