首页 > 其他分享 >手写实现call,apply,bind

手写实现call,apply,bind

时间:2023-02-03 10:11:06浏览次数:33  
标签:function ... const context bind args call key apply

const globalThis = typeof window !== 'undefined' ? window : global;

Function.prototype.myCall = function (context, ...args) {
  if (typeof this !== 'function') {
    throw new TypeError('Type error');
  }  
  context = context || global;
  const key = Symbol('key');
  context[key] = this;
  const res = context[key](...args);
  delete context[key];
  return res;
}

Function.prototype.myApply = function (context = globalThis, args = []) {
  if (typeof this !== 'function') {
    throw new TypeError('Type error');
  }  
  context = context || global;
  const key = Symbol('key');
  context[key] = this;
  const res = context[key](...args);
  delete context[key];
  return res;
  
}

Function.prototype.myBind = function (context = globalThis, ...args) {
  if (typeof this !== 'function') {
    throw new TypeError('Type error');
  }  
  let self = this;
  return function F() {
    if (this instanceof F) {
      return new self(...args, ...arguments);
    }

    return self.apply(context, [...args, ...arguments]);
  }

}

标签:function,...,const,context,bind,args,call,key,apply
From: https://www.cnblogs.com/laiyaoweb/p/17088243.html

相关文章