『es6 bind』bind实现

775 阅读1分钟

Function.prototype.bind

bind

bind()  方法创建一个新的函数,在 bind() 被调用时,这个新函数的 this 被指定为 bind() 的第一个参数,而其余参数将作为新函数的参数,供调用时使用。MDN

function fn() {
  console.log("[console value]", this.value);
}

const obj = {
  value: "this is obj.value",
};

const bindFn = fn.bind(obj);

bindFn() // [console value] this is obj.value
image.png

bindSimply

Function.prototype.bindSimply = function (obj) {
  const fn = this;
  return function () {
    fn.call(obj);
  };
};

const bindSM = fn.bindSimply(obj);

bindSM() // [console value] this is obj.value

✅ 没问题

image.png

arguments

fn = function fn(arg1, arg2) {
  console.log("[console value]", this.value);
  console.log("[console arg1]", arg1);
  console.log("[console arg2]", arg2);
}

Function.prototype.bindSimply = function (obj) {
  const fn = this;
  return function () {
    fn.call(obj, ...arguments);
  };
};

const bindSMMen = fn.bindSimply(obj);

bindSMMen("gay1", "gay2");
// [console value] this is obj.value
// [console arg1] gay1
// [console arg2] gay2
image.png

Currying

Function.prototype.bindSimply = function (obj, ...args) {
  const fn = this;
  return function () {
    fn.call(obj, ...args, ...arguments);
  };
};

fn = function fn() {
  console.log("[console value]", this.value);
  console.log("[console arguments]", arguments);
};

const bindSMMenMen = fn.bindSimply(obj, "gay3", "gay4");

bindSMMenMen("gay1", "gay2");
// [console value] this is obj.value
// [console arguments] [Arguments] { '0': 'gay3', '1': 'gay4', '2': 'gay1', '3': 'gay2' }
image.png

new

Function.prototype.bindSimply = function (obj, ...args) {
  const fn = this;
  return function () {
    if (new.target) return new fn(...arg, ...arguments);
    fn.call(obj, ...args, ...arguments);
  };
};

prototype

image.png
Function.prototype.bindSimply = function (obj, ...args) {
  const fn = this;
  function res() {
    if (new.target) return new fn(...arg, ...arguments);
    fn.call(obj, ...args, ...arguments);
  }
  res.prototype = undefined;
  return res;
};

const bindSMNoeye = fn.bindSimply(obj);

bindSMNoeye.prototype
image.png