dragonwong / blog

a blog based on github page
dragonwong.github.io/blog/
9 stars 4 forks source link

震惊!99% 的 JS 程序员竟然不了解 bind 方法... #1

Open dragonwong opened 7 years ago

dragonwong commented 7 years ago

先别让我去 UC,先看看这段代码:

const objA = {
  num: 1,
};
const objB = {
  num: 2,
};

function fn() {
  console.log(this.num);
}

fn = fn.bind(objA);
fn = fn.bind(objB);

fn();

答案是啥?

竟然是...

1


在 @malcolmyu 同学的点拨下,猜测 bind 方法的实际返回一个内部使用 call 的匿名函数:

function bind(fn, context) {
  return function() {
    fn.call(context);
  };
}

下面通过实现 mybind 方法模拟 bind

Function.prototype.mybind = function(context) {
  return () => {
    this.call(context);
  }
}

验证下:

Function.prototype.mybind = function(context) {
  return () => {
    this.call(context);
  }
}

const objA = {
  num: 1,
};
const objB = {
  num: 2,
};

function fn() {
  console.log(this.num);
}

fn = fn.mybind(objA);
fn = fn.mybind(objB);

fn(); // 打印 1

哈哈,一毛一样。