前端 2018-06-09 10:48:34

JS中的bind()用法

语法

fun.bind(thisArg, arg1, arg2, ...)

参数

  1. thisArg
    当绑定函数被调用时,该参数会作为原函数运行时的 this 指向。当使用new 操作符调用绑定函数时,该参数无效。
  2. arg1, arg2, ...
    当绑定函数被调用时,这些参数将置于实参之前传递给被绑定的方法。

返回值

返回由指定的this值和初始化参数改造的原函数拷贝

示例

function f(){
  return this.a;
}

var g = f.bind({a:"azerty"});
console.log(g()); // azerty

var h = g.bind({a:'yoo'}); // bind只生效一次!
console.log(h()); // azerty

var o = {a:37, f:f, g:g, h:h};
console.log(o.f(), o.g(), o.h()); // 37, azerty, azerty

将原先指向window的this重新指向{a:"azerty"} 对象
注意:bind只生效一次!