这是我参与更文挑战的第22天,活动详情查看: 更文挑战
什么是bind()
bind这个单词的意思,直译过来是绑定、捆绑的意思,而这个含义也是在js这个方法的核心思想。
一句话描述bind:
bind() 方法会创建一个新函数。当这个新函数被调用时,bind() 的第一个参数将作为它运行时的 this,之后的一系列参数将会在传递的实参前传入作为它的参数。
—-描述引至MDN
无论的方法名的直译、还是对方法的描述,都在告诉我们,这个方法会与他的第一个参数绑定,并将这个参数作为this的指向。
也就是重定向this
举个栗子
再写demo之前,先看看调用已实现的JS中的bind方法的效果,不会的小伙伴也可以先跟着敲一下。
var foo = {
val: 1
}
function bar(){
console.log(this.val);
}
// 返回一个函数
var bindFoo = bar.bind(foo);
bindFoo(); // 1
复制代码
了解了bind方法的使用之后,来实现一下自己的bind吧
Function.prototype.myBind = function(context){
context.fn = this;
return function(){
return context.fn()
}
}
var foo = {val: 1};
function bar(){ console.log(this.val) };
var fn = bar.myBind(foo);
fn(); // 1
复制代码
效果图
可以看到,能初步的实现效果了,但是有个问题,看最下面这行,原对象foo中多了一个函数。
这是因为在初步实现的时候,我们将函数bar()插入到对象中去了。那么这里为了原汁原味的实现,就需要对他进行处理了。
Function.prototype.bind2 = function (context) {
var _this = this;
return function () {
return _this.apply(context);
}
}
复制代码
到这里,基本的功能就实现了,那么再进一步就是参数的处理了。
Function.prototype.bind2 = function (context) {
var _this = this;
var args = Array.prototype.slice.call(arguments, 1);
var fNOP = function () {};
var fBound = function () {
var bindArgs = Array.prototype.slice.call(arguments);
return _this.apply(this instanceof fNOP ? this : _this, args.concat(bindArgs));
}
fNOP.prototype = this.prototype;
fBound.prototype = new fNOP();
return fBound;
}
复制代码
总结
到这里,基本就实现了一个bind了,虽然实际开发中,不需要我们手动实现,但是学习的时候,多动手,跟着实现一遍有注意加深理解,帮助我们学习。
加油吧。
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END