bind

一句话介绍 bind:

bind() 方法会创建一个新函数。当这个新函数被调用时,bind() 的第一个参数将作为它运行时的 this,之后的一序列参数将会在传递的实参前传入作为它的参数。(来自于 MDN )

由此我们可以首先得出 bind 函数的两个特点:

  1. 返回一个函数
  2. 可以传入参数

返回函数的模拟实现

从第一个特点开始,我们举个例子:

var foo = {
value: 1
}; function bar() {
console.log(this.value);
} // 返回了一个函数
var bindFoo = bar.bind(foo); bindFoo(); // 1

关于指定 this 的指向,我们可以使用 call 或者 apply 实现,关于 call 和 apply 的模拟实现,可以查看《JavaScript深入之call和apply的模拟实现》。我们来写第一版的代码:

// 第一版
Function.prototype.bind2 = function (context) {
var self = this;
return function () {
self.apply(context);
} }

传参的模拟实现

接下来看第二点,可以传入参数。这个就有点让人费解了,我在 bind 的时候,是否可以传参呢?我在执行 bind 返回的函数的时候,可不可以传参呢?让我们看个例子:

var foo = {
value: 1
}; function bar(name, age) {
console.log(this.value);
console.log(name);
console.log(age); } var bindFoo = bar.bind(foo, 'daisy');
bindFoo('18');
// 1
// daisy
// 18

函数需要传 name 和 age 两个参数,竟然还可以在 bind 的时候,只传一个 name,在执行返回的函数的时候,再传另一个参数 age!

这可咋办?不急,我们用 arguments 进行处理:

// 第二版
Function.prototype.bind2 = function (context) { var self = this;
// 获取bind2函数从第二个参数到最后一个参数
var args = Array.prototype.slice.call(arguments, 1); return function () {
// 这个时候的arguments是指bind返回的函数传入的参数
var bindArgs = Array.prototype.slice.call(arguments);
self.apply(context, args.concat(bindArgs));
} }

构造函数效果的模拟实现

完成了这两点,最难的部分到啦!因为 bind 还有一个特点,就是

一个绑定函数也能使用new操作符创建对象:这种行为就像把原函数当成构造器。提供的 this 值被忽略,同时调用时的参数被提供给模拟函数。

也就是说当 bind 返回的函数作为构造函数的时候,bind 时指定的 this 值会失效,但传入的参数依然生效。举个例子:

var value = 2;

var foo = {
value: 1
}; function bar(name, age) {
this.habit = 'shopping';
console.log(this.value);
console.log(name);
console.log(age);
} bar.prototype.friend = 'kevin'; var bindFoo = bar.bind(foo, 'daisy'); var obj = new bindFoo('18');
// undefined
// daisy
// 18
console.log(obj.habit);
console.log(obj.friend);
// shopping
// kevin

注意:尽管在全局和 foo 中都声明了 value 值,最后依然返回了 undefind,说明绑定的 this 失效了,如果大家了解 new 的模拟实现,就会知道这个时候的 this 已经指向了 obj。

(哈哈,我这是为我的下一篇文章《JavaScript深入系列之new的模拟实现》打广告)。

所以我们可以通过修改返回的函数的原型来实现,让我们写一下:

// 第三版
Function.prototype.bind2 = function (context) {
var self = this;
var args = Array.prototype.slice.call(arguments, 1); var fBound = function () {
var bindArgs = Array.prototype.slice.call(arguments);
// 当作为构造函数时,this 指向实例,此时结果为 true,将绑定函数的 this 指向该实例,可以让实例获得来自绑定函数的值
// 以上面的是 demo 为例,如果改成 `this instanceof fBound ? null : context`,实例只是一个空对象,将 null 改成 this ,实例会具有 habit 属性
// 当作为普通函数时,this 指向 window,此时结果为 false,将绑定函数的 this 指向 context
self.apply(this instanceof fBound ? this : context, args.concat(bindArgs));
}
// 修改返回函数的 prototype 为绑定函数的 prototype,实例就可以继承绑定函数的原型中的值
fBound.prototype = this.prototype;
return fBound;
}

如果对原型链稍有困惑,可以查看《JavaScript深入之从原型到原型链》

构造函数效果的优化实现

但是在这个写法中,我们直接将 fBound.prototype = this.prototype,我们直接修改 fBound.prototype 的时候,也会直接修改绑定函数的 prototype。这个时候,我们可以通过一个空函数来进行中转:

// 第四版
Function.prototype.bind2 = function (context) { var self = this;
var args = Array.prototype.slice.call(arguments, 1); var fNOP = function () {}; var fBound = function () {
var bindArgs = Array.prototype.slice.call(arguments);
self.apply(this instanceof fNOP ? this : context, args.concat(bindArgs));
} fNOP.prototype = this.prototype;
fBound.prototype = new fNOP();
return fBound;
}

到此为止,大的问题都已经解决,给自己一个赞!o( ̄▽ ̄)d

三个小问题

接下来处理些小问题:

1.apply 这段代码跟 MDN 上的稍有不同

在 MDN 中文版讲 bind 的模拟实现时,apply 这里的代码是:

self.apply(this instanceof self ? this : context || this, args.concat(bindArgs))

多了一个关于 context 是否存在的判断,然而这个是错误的!

举个例子:

var value = 2;
var foo = {
value: 1,
bar: bar.bind(null)
}; function bar() {
console.log(this.value);
} foo.bar() // 2

以上代码正常情况下会打印 2,如果换成了 context || this,这段代码就会打印 1!

所以这里不应该进行 context 的判断,大家查看 MDN 同样内容的英文版,就不存在这个判断!

2.调用 bind 的不是函数咋办?

不行,我们要报错!

if (typeof this !== "function") {
throw new Error("Function.prototype.bind - what is trying to be bound is not callable");
}

3.我要在线上用

那别忘了做个兼容:

Function.prototype.bind = Function.prototype.bind || function () {
……
};

当然最好是用 es5-shim 啦。

最终代码

所以最最后的代码就是:

Function.prototype.bind2 = function (context) {

    if (typeof this !== "function") {
throw new Error("Function.prototype.bind - what is trying to be bound is not callable");
} var self = this;
var args = Array.prototype.slice.call(arguments, 1); var fNOP = function () {}; var fBound = function () {
var bindArgs = Array.prototype.slice.call(arguments);
self.apply(this instanceof fNOP ? this : context, args.concat(bindArgs));
} fNOP.prototype = this.prototype;
fBound.prototype = new fNOP();
return fBound;
}

bind的模拟实现的更多相关文章

  1. bind()的模拟实现

    上一篇对call和apply的模拟实现做了一个梳理,可参见:模拟实现call.apply,下面将具体研究一下bind啦啦啦 1. bind和call/apply的差别 bind方法会创建一个新函数,返 ...

  2. jquery 动态绑定bind()及模拟鼠标点击A链接

    近来自觉前端有小小进步,幸而记之. 1.两个 css class 紧挨在一起 则在html元素中,要同时拥有这两个class,才能起作用 .block.db{ background-image:url ...

  3. js-new、object.create、bind的模拟实现【转载备忘】

    //创建Person构造函数,参数为name,age function Person(name,age){ this.name = name; this.age = age; } function _ ...

  4. bind函数作用、应用场景以及模拟实现

    bind函数 bind 函数挂在 Function 的原型上 Function.prototype.bind 创建的函数都可以直接调用 bind,使用: function func(){ consol ...

  5. Javascript中的bind详解

    前言 用过React的同学都知道,经常会使用bind来绑定this. import React, { Component } from 'react'; class TodoItem extends ...

  6. 第19课 lambda vs std::bind

    一. std::bind (一)std::bind实现的关键技术 [编程实验]探索bind原理,实现自己的bind函数 #include <iostream> #include <t ...

  7. 【Web】浅析JQuery的apply(), call(), bind()方法

    原文地址:https://blog.csdn.net/whuzxq/article/details/64166253 由于在理解this的用法的时候多次出现了这几个方法,个人对这几个方法理解的不是很透 ...

  8. 如何用apply实现一个bind?

    面试题:如何用apply实现一个bind? Function.prototype._bind = function(target) { // 保留调用_bind方法的对象 let _this = th ...

  9. apply call bind的用法与实现

    概念 apply call 和bind 允许为不同的对象分配和调用属于一个对象的函数/方法.同时它们可以改变函数内 this 的指向. 区别 apply 和 call 接收的参数形式不同 apply ...

随机推荐

  1. 【剑指offer】孩子们的游戏(圆圈中最后剩下的数)

    题目描述 每年六一儿童节,牛客都会准备一些小礼物去看望孤儿院的小朋友,今年亦是如此.HF作为牛客的资深元老,自然也准备了一些小游戏.其中,有个游戏是这样的:首先,让小朋友们围成一个大圈.然后,他随机指 ...

  2. 百度前端技术学院-task1.10源代码

    任务十的源代码,其实有github的,但就是不知道怎么弄,近期会学会的.在IE和firefox上检测运行良好. <!DOCTYPE html> <html lang="en ...

  3. 【在 Nervos CKB 上做开发】Nervos CKB 脚本编程简介[4]:在 CKB 上实现 WebAssembly

    作者:Xuejie 原文链接:https://xuejie.space/2019_10_09_introduction_to_ckb_script_programming_wasm_on_ckb/ N ...

  4. 示例:WPF中自定义StoryBoarService在代码中封装StoryBoard、Animation用于简化动画编写

    原文:示例:WPF中自定义StoryBoarService在代码中封装StoryBoard.Animation用于简化动画编写 一.目的:通过对StoryBoard和Animation的封装来简化动画 ...

  5. Asp.Net Core中使用GDI+绘图提示gdiplus库找不到的问题

    参考  https://www.cnblogs.com/VirtualMJ/p/9917916.html 文章中   1 2 3 yum install -y epel-release yum mak ...

  6. tomcat端口修改后在Eclipse中启动无效问题解决

    原文:https://blog.csdn.net/yangyiqian/article/details/40262039 问题:在conf目录修改了server.xml配置中的节点  <Conn ...

  7. C#中真正的属性

    引言 我们以前课堂上说的类当中的“属性”,其实官方叫法是“字段”或者“域”域(Field).正常使用,把它们当属性理解更加方便快捷,也没有什么问题. 如果要在微软的mvc中充分利用类带来的便利,就有必 ...

  8. ubuntu ufw相关命令

    引自:http://www.cnblogs.com/jiangyao/archive/2010/05/19/1738909.html 就这句话就够了,下面的可以不看 sudo  ufw enable| ...

  9. Geany——Python配置

    Geany是一个很不错的编辑器,操作很简单,这里记录一下Geany的入手设置(在下是一个Python程序猿,就以Python为例): 1:新建:选择 下拉菜单中的  main.py  ,然后就能生成P ...

  10. 2019 哔哩哔哩java面试笔试题 (含面试题解析)

      本人5年开发经验.18年年底开始跑路找工作,在互联网寒冬下成功拿到阿里巴巴.今日头条.哔哩哔哩等公司offer,岗位是Java后端开发,因为发展原因最终选择去了哔哩哔哩,入职一年时间了,也成为了面 ...