Skip to content

关于bind实现的一点建议 #2

@XuRuiXi

Description

@XuRuiXi
Function.prototype.myBind = function(context){
  if (context === null || context === undefined) {
    // this参数如果是null/undefined,就指向window,node环境为global
    try {
      context = window;
    } catch(e){
      context = global;
    }
  } else {
    context = Object(context);
  }
  const symbolKey = Symbol('特殊键,用来存储原始this,即原始function');
  context[symbolKey] = this;
  return function(...params){
    context[symbolKey](...params);
    Reflect.deleteProperty(context, symbolKey);
  };
}

这样可以摆脱对call的依赖,而且保持和myCall、myApply实现原理的一致性

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions