js手写call,apply,bind方法改变this的指向问题

123 阅读1分钟

1:手写call函数

Function.prototype.myCall = function (target, ...args) {
  // this 指向调用 myCall函数的对象
  if (typeof this !== "function") {
    throw new TypeError("not a function");
  }
  target = target || window;
  target.fnn = this; // 隐式绑定,改变构造函数的调用者间接改变 this 指向
  let result = target.fnn(...args);
  return result;
};
// 测试
let obj = { name: 123 };
function foo(...args) {
  console.log(this.name, args);
}
foo.myCall(obj, "222");//123[222]

2:手写apply函数

Function.prototype.myApply = function (target, ...args) {
  // this 指向调用 myCall函数的对象
  if (typeof this !== "function") {
    throw new TypeError("not a function");
  }
  target = target || window;
  target.fnn = this; // 隐式绑定,改变构造函数的调用者间接改变 this 指向
  let result = target.fnn(...args);
  return result;
};
// 测试
let obj = { name: 123 };
function foo(...args) {
  console.log(this.name, ...args);
}
foo.myApply(obj, [111, 222, 333]);

此方法的和call的实现基本一致

3:手写bind函数

Function.prototype.Mybind = function (target, array) {
  target.fun = this;
  let back = target.fun(...array);
  return back;
};
let object = {
  a: 1,
};
function ljy(...arg) {
  return this.a + arg;
}
let a = ljy.Mybind(object, [1, 2, 3]);
console.log(a);