bind 可以改变方法中的this指向
/**** * * 语法:fun.bind(thisArg[, arg1[, arg2[, ...]]]) * 可以利用 bind() 把 fun() 方法中的 this 绑定到 thisArg 对象上, * 并且还可以传进去额外的参数,当返回的绑定函数被调用时, * 这些额外的参数会自动传入绑定函数。 */ var module = { a : 2, getA : function () { return this.a; } } //getA方法中的this指向的是module,所以打印的是2 console.log(module.getA()); //2 //将方法单独拿出来 var getA1 = module.getA; //方法中的this,这时指向的是全局对象,全局对象没有a,所以打印undefined console.log(getA1()); // undefined //bind返回的是个方法,只是方法的this,指向发生改变了,始终指向的是bind的对象 var getA2 = module.getA.bind(module); console.log(getA2());
var a = { b: function() { var func = function() { console.log(this.c); } func(); }, c: ‘hello‘ } a.b(); // undefined 这里的this指向的是全局作用域 console.log(a.c); // hello console.log("***********************") var a = { b: function() { var _this = this; // 通过赋值的方式将this赋值给that var func = function() { console.log(_this.c); } func(); }, c: ‘hello‘ } a.b(); // hello console.log(a.c); // hello console.log("***********************") // 使用bind方法一 var a = { b: function() { var func = function() { console.log(this.c); }.bind(this); func(); }, c: ‘hello‘ } a.b(); // hello console.log(a.c); // hello // 使用bind方法二 var a = { b: function() { var func = function() { console.log(this.c); } func.bind(this)(); }, c: ‘hello‘ } a.b(); // hello console.log(a.c); // hello console.log("***********************") // 分析:这里的bind方法会把它的第一个实参绑定给f函数体内的this,所以里的this即指向{x:1}对象; // 从第二个参数起,会依次传递给原始函数,这里的第二个参数2即是f函数的y参数; // 最后调用m(3)的时候,这里的3便是最后一个参数z了,所以执行结果为1+2+3=6 // 分步处理参数的过程其实是一个典型的函数柯里化的过程(Curry) function f(y,z){ return this.x+y+z; } var m = f.bind({x:1},2); console.log(m(3)); // 6
原文:https://www.cnblogs.com/moris5013/p/10782323.html