Skip to content

[总结] bind, apply, call 的使用及实现 #21

@duyue6002

Description

@duyue6002

apply / call

区别

func.call(this, arg1, arg2);
func.apply(this, [arg1, arg2]);

参数数量固定时用call,不确定时用apply。希望改变上下文环境后立即执行,用apply / call

实现 apply

Function.prototype.myApply = function(context = window, arguments) {
  if (!context) {
    context = Object.create(null);
  }
  context.fn = this;
  if (arguments) {
    context.fn(...arguments);
  } else {
    context.fn();
  }
  delete context.fn;
};

实现 call

Function.prototype.myApply = function(context = window, ...arguments) {
  if (!context) {
    context = Object.create(null);
  }
  context.fn = this;
  if (arguments) {
    context.fn(...arguments);
  } else {
    context.fn();
  }
  delete context.fn;
};

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions