Skip to content

call、apply、bind方法的实现 #3

@Chersquwn

Description

@Chersquwn

call

Function.prototype.call2 = function(context: any, ...args: any[]) {
  const ctx = context || window

  ctx.fn = this

  const res = ctx.fn(...args)

  Reflect.deleteProperty(ctx, 'fn')

  return res
}

apply

Function.prototype.apply2 = function(context: any, args: any[] = []) {
  const ctx = context || window

  ctx.fn = this

  const res = ctx.fn(...args)

  Reflect.deleteProperty(ctx, 'fn')

  return res
}

bind

Function.prototype.bind2 = function(context: any, ...args1: any[]) {
  const ctx = context || window
  const fn = this

  return function F(...args2: any[]) {
    return fn.apply(this instanceof F ? this : ctx, [...args1, ...args2])
  }
}

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