Skip to content
On this page

手写call、apply、bind

js
// 实现call、apply、bind
Function.prototype.myCall = function (context, ...args) {
  context = context || window;
  const fnSymbol = Symbol();
  context[fnSymbol] = this;
  const result = context[fnSymbol](...args);
  delete context[fnSymbol];
  return result;
};

Function.prototype.myApply = function (context, argsArray) {
  context = context || window;
  const fnSymbol = Symbol();
  context[fnSymbol] = this;
  const result = argsArray ? context[fnSymbol](...argsArray) : context[fnSymbol]();
  delete context[fnSymbol];
  return result;
};

Function.prototype.myBind = function (context, ...args) {
  const fn = this;
  return function (...bindArgs) {
    return fn.myCall(context, ...args, ...bindArgs);
  };
};

// call、apply、bind区别:
// call和apply都是立即执行函数,bind是返回一个新函数
// call传参是逗号分隔,apply传参是数组

// 示例:
function greet(greeting, punctuation) {
  return greeting + ', ' + this.name + punctuation;
}
const person = { name: 'Alice' };
console.log(greet.myCall(person, 'Hello', '!')); // Hello, Alice!
console.log(greet.myApply(person, ['Hi', '...'])); // Hi, Alice...
const boundGreet = greet.myBind(person, 'Hey');
console.log(boundGreet('?')); // Hey, Alice?