javascript bind

bind的作用和apply,call类似都是改变函数的execute context,也就是runtime时this关键字的指向。但是使用方法略有不同。一个函数进行bind后可稍后执行。

定义:

function.bind(thisArg[,arg1[,arg2[,argN]]])

返回值 依然是function

这里与apply和call是不同的,apply和call是直接执行function,bind仅是将参数和thisArg缓存给function,却不会去触发

function testFun(name1 , name2, name3, name4){ 
console.log(name1+" ; " +name2+" ; " +name3+" ; " +name4 ); 
}

var test1 = testFun.bind(null,1,2);
var test2 = test1.bind(null,3);
test2(4);

结果:
1 ; 2 ; 3 ; 4 

可以看到bind是把参数一个个压进堆栈中去保存起来的

另外,bind也可以使用内置函数或者说可以用原型链调用

Array.prototype.slice.bind

换句话说,就是可以在不实例化类的情况下,直接调用共有方法(即 原型链上的方法,Person.prototype.display.bind)。