Handwritten js call, apply, bind

Handwritten js call, apply, bind

/**
 * https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Function/call
 *
 * call() 方法使用一个指定的 this 值和单独给出的一个或多个参数来调用一个函数。
 */
Function.prototype.Call = function (target, ...org) {
    
    
  // this 指的是调用的函数 ,这里是下面的Foo函数
  target.fn = this
  target.fn(...org)
}

/**
 * https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Function/apply
 *
 * apply() 方法调用一个具有给定this值的函数,以及作为一个数组(或类似数组对象)提供的参数。
 */

Function.prototype.Apply = function (target, org) {
    
    
  // this 指的是调用的函数 ,这里是下面的Foo函数
  target.fn = this
  target.fn(...org)
}

/**
 * https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Function/bind
 *
 * bind() 方法创建一个新的函数,在 bind() 被调用时,这个新函数的 this 被指定为 bind() 的第一个参数,而其余参数将作为新函数的参数,供调用时使用。
 *
 * 绑定函数也可以使用 new 运算符构造,它会表现为目标函数已经被构建完毕了似的。提供的 this 值会被忽略,但前置参数仍会提供给模拟函数。
 */

Function.prototype.Bind = function (target, ...org) {
    
    
  // this 指的是调用的函数 ,这里是下面的Foo函数
  const self = this
  const Fun = function () {
    
    }
  function Bound(...newOrg) {
    
    
    // 普通调用的话,this指的是window 。 作为构造函数调用的话,this指的是构造函数Foo的实例 Foo {}
    return self.apply(this instanceof self ? this : target, [...org, ...newOrg])
  }
  Fun.prototype = this.prototype
  Bound.prototype = new Fun()
  return Bound
}

const obj = {
    
     name: 'xm' }
const params = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

function Foo(...args) {
    
    
  this.name = args[0]
  console.log(args)
}

Foo.Call(obj, ...params)
//  [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

Foo.Apply(obj, params)
//  [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

const func = Foo.Bind(obj, ...params)
const f = func(5000)
// [(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 5000)]

const n = new func(5000)
// Foo { name: 1 }

Guess you like

Origin blog.csdn.net/qq_39953537/article/details/106055875