bind以及手动实现bind

简介: bind以及手动实现bind

什么是 bind

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

var foo = {
  value: 1,
};

function bar() {
  console.log(this.value);
}

// 返回了一个函数
var bindFoo = bar.bind(foo);

bindFoo(); // 1

手动实现 bind

手动实现 bind 有以下几个需要注意的地方

  1. 返回的是一个函数
  2. 可以传入参数
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);
    return self.apply(
      this instanceof fNOP ? this : context,
      args.concat(bindArgs)
    );
  };

  fNOP.prototype = this.prototype;
  fBound.prototype = new fNOP();
  return fBound;
};
目录
相关文章
|
11月前
|
前端开发
v-bind与v-model的区别
v-bind与v-model的区别
134 0
|
C++
c++bind函数使用
c++bind函数使用
114 1
|
网络协议
关于socket bind的理解
socket bind的ip和port的选择
2855 0
ES6—26:bind方法应用
ES6—26:bind方法应用
124 0
ES6—26:bind方法应用
|
网络协议
|
域名解析 缓存 网络协议
|
缓存 网络协议 数据库
|
Linux Perl C++