JS中bind()
2020-02-17 本文已影响0人
书虫和泰迪熊
Function.prototype.bind()
一. 什么是bind()方法?
bind()方法创建了一个新的函数(称为绑定功函数,BF),在bind()被调用时,这个新函数的this被指定为bind()方法的第一个参数,而bind()方法的其余参数将作为新函数的参数,供调用时使用。
返回值:返回一个原函数的拷贝,并拥有指定的this值和初始参数。
简单理解:fun.bind(obj) 可以理解为 obj.fun(),这时,fun函数体内的this会指向obj
二. 一起来看例子吧
例子1:
var a = {
b: function() {
var func = function() {
console.log(this.c);
}
func();
},
c: 'hello!'
}
a.b(); //undefined
// 因为这里的 this 指向的是全局作用域,所以会返回 undefined
var a = {
b: function() {
var that = this;
var func = function() {
console.log(that.c);
}
func();
},
c: 'hello!'
}
a.b(); */ // hello!
// 通过赋值的方式将 this传给 that
var a = {
b: function() {
var func = function() {
console.log(this.c);
}.bind(this)
func();
},
c: 'hello!'
}
a.b(); //hello!
// 或者下面这种方式绑定
var a = {
b: function() {
var func = function() {
console.log(this.c);
}
func.bind(this)();
},
c: 'hello!'
}
a.b(); //hello!
例子2:
function f(y, z) {
return this.x + y + z;
}
var m = f.bind({x: 1}, 2)
console.log(m(3)); //6
// 这里的bind方法会把第一个实参绑定给f函数体内的this,所以这里的this即指向{x: 1},
// 从第二个参数起,会依次传递给元素函数,所以这里的第二个参数2,即是f函数发y参数,
// 最后调用m(3)的时候值了的3便是最后一个参数 z 了, 则结果为 1 + 2 + 3 = 6
// 这里的分布处理即体现了函数的柯里化过程(Curry)
例子3:
var a = document.write;
a('hello');
//Error
a.bind(document)('hello');
//hello
a.call(document, 'hello');
//hello
// 这里直接调用a的话,this指向的是global或window对象,所以会报错,通过bind或者call的方式绑定this至document对象,即可正常调用可以用bind的方式预定义参数
例子4:
function list(){
return Array.prototype.slice.call(arguments);
}
var list1 = list(1, 2, 3);
//[1, 2, 3]
//预定义参数
var a = list.bind(undefined, 10);
var list2 = a();
//[10]
var list3 = a(1, 2, 3);
//[10, 1, 2, 3]
// 这里的Array.prototype.slice.call(arguments)是用来将参数由类数组转换为真正的数组,a的第一个参数undefined表示this的指向,第二个参数10即表示list中真正的第一个参数,依次类推
三. 实现自己的bind方法!!!
var b = {name: 'ding'}
Function.prototype.my_bind = function(context) {
var self = this; // 指向 fn, 此处的self被下面的匿名函数一直引用着,就行成了闭包,柯里化是闭包的应用之一
return function() {
return self.apply(context, [].slice.call(arguments))
}
}
function fn(value) {
return console.log(this.name, value); //此处this即content即b
}
var t = fn.my_bind(b); // 传入实参数b用形参content接収 当做将要apply函数的执行上下文, 匿名函数延迟执行
console.log(t)
t(333) //执行匿名函数, 输出结果 ding 333
// 即预先绑定对象并返回函数,之后在执行函数,符合柯里化
- 参考链接:
https://blog.csdn.net/kongjunchao159/article/details/59113129 - 相关内容链接:
前端之函数柯里化Currying https://juejin.im/post/5c243574518825741e7c33ed
你遇到过[ ].slice.call()吗?https://www.jianshu.com/p/ae57baecc57d
JS中call()和apply() https://www.jianshu.com/p/aa2eeecd8b4f
········································································································zhongyuxiewanle~~~
