call,apply,bind函数

·  阅读 39
Function.prototype.myCall = function (thisArg, ...args) {
  const fn = Symbol("fn");
  thisArg = Object(thisArg) ?? window;
  thisArg[fn] = this;
  const result = thisArg[fn](...args);
  delete thisArg[fn];
  return result;
};
function foo(num1, num2) {
  return num1 + num2;
}
console.log(foo.myCall(null, 1, 2));

// Function.prototype.myApply = function (thisArg, args) {
//   const fn = Symbol("fn");
//   thisArg = Object(thisArg) ?? window;
//   thisArg[fn] = this;
//   const result = thisArg[fn](...args);
//   delete thisArg[fn];
//   return result;
// };
// function foo(num1, num2, num3) {
//   return num1 + num2 + num3;
// }
// console.log(foo.myApply("abc", [4, 5, 1]));

// Function.prototype.mybind = function (thisArg, ...args) {
//   const fn = Symbol("fn");
//   thisArg = Object(thisArg) ?? window;
//   thisArg[fn] = this;
//   return function (...argArray) {
//     argArray = argArray.concat(args);
//     const result = thisArg[fn](...argArray);
//     delete thisArg[fn];
//     return result;
//   };
// };
// function foo(num1, num2, num3) {
//   return num1 + num2 + num3;
// }
// console.log(foo.mybind("obj", 2, 3)(5));

复制代码
分类:
前端
标签:
分类:
前端
标签:
收藏成功!
已添加到「」, 点击更改