手写一个 call,apply,bind 吧

这篇文章是手写实现xxx功能部分的第一篇,后续会陆续更新其他的。

目录传送门 github地址

一、call方法

考察知识点: call方法基础用法,Function原型对象,解构用法, JS方法中this的指向, arguments等

function sayName(p) {
  console.log(this.name)
  console.log(p)
  return `${p}${this.name}`
}

// ES6版,比较简单
Function.prototype.selfCall = function(ctx, ...args) {
  if (typeof this !== 'function') {
    throw new Error('you must use call with function')
  }
   // ctx = ctx || window || global // 这个写法是为了在NodeJS中运行,不过这个并非这个问题的关键
  ctx = ctx || window
  // 强绑定上ctx为执行上下文,这里为了为了防止方法名称冲突,我定义这个方法名称为_fn,不过这个并不是这个问题的关键考察点
  ctx._fn = this
  const res = ctx._fn(...args)
  // 删除这个,防止影响外部的对象正常运行
  delete ctx._fn
  // 返回值也要注意
  return res
}


// ES5版
Function.prototype.es5call = function(ctx) {
 if (typeof this !== 'function') {
    throw new Error('you must use call with function')
  }
  ctx = ctx || window
  var args = []
  // 收集参数
  for (var i = 1; i < arguments.length; i++) {
    args.push('arguments[' + i + ']')
  }
  var argstr = args.join(',')
  ctx._fn = this
  // ES5 由于无法通过解构的形式传入参数,只能通过字符串拼接然后再通过eval来执行
  var res =  eval('ctx._fn(' + argstr + ')')
  delete ctx._fn
  return res
}

var obj = {name: 'wyh'}
// 验证结果
console.log(sayName.call(obj, 'xxx'))
console.log(sayName.selfCall(obj, 'xxx')) 
console.log(sayName.es5call(obj, 'xxx')) 

二、apply方法

考察知识点: apply方法用法


var obj = {
  name: 'wyh'
}

function say() {
  console.log(arguments[1] + arguments[2]) // expect 5
  return this.name
}

Function.prototype.es6apply = function(ctx, args) {
  if (typeof this !== 'function') {
    throw new Error('you must use apply with function')
  }
  ctx = ctx || window
  ctx._fn = this
  const res = ctx._fn(...args)
  delete ctx._fn
  return res
}

Function.prototype.es5apply = function(ctx, args) {
  if (typeof this !== 'function') {
    throw new Error('you must use apply with function')
  }
  ctx = ctx || window
  ctx._fn = this
  var res
  if (!args || !args.length) {
    res = ctx._fn()
  } else {
    var argStr = args.reduce(function(prev, current, currentIndex) {
      return prev + ",args[" + currentIndex + "]"
    }, '')
    argStr = argStr.substr(1)
    res = eval("ctx._fn(" + argStr + ")")
  }
  delete ctx._fn
  return res
}

console.log(say.apply(obj, [1,2,3,4])) // 5 , wyh
console.log(say.es6apply(obj, [1,2,3,4])) // 5 , wyh
console.log(say.es5apply(obj, [1,2,3,4])) // 5 , wyh

三、bind方法

考察知识点: bind方法的用法

bind方法是不同于call方法和apply方法的,bind方法会返回一个新的函数。这个方法的接收参数形式和意义与call方法一样,不同的是,bind会将接收的第一个参数作为返回的函数的this对象。bind方法是函数珂里化的一个典型例子。

对于bind,我会特殊对待,由浅到深完成实现它的过程

// 首先定义一些基础的数据方便后面使用
var person = {
  name: 'wyh',
  sayName(n) {
    return n + this.name
  },
  calc(a,b) {
    console.log(this.name)
    return a + b
  }
}

var person2 = {
  name: 'person2'
}

1、 bind 辅助函数形式

function _bind(fn, ctx, ...args) {
  return function() {
    return fn.apply(ctx, args)
  }
}

console.log(_bind(person.sayName, person2, 'nihao')()) // nihaoperson2

这个只是为了更方便大家去理解bind函数的工作模式

2、使用apply/call 实现bind函数 这个也是很简单的

Function.prototype.applybind = function(ctx, ...args) {
  if (typeof this !== 'function') {
    throw new Error('you must use bind with function')
  }
  ctx = ctx || window
  var self = this
  return function() {
    return self.apply(ctx, args)
  }
}

3、不使用强绑定形式

// ES6版
Function.prototype.es6bind = function(ctx, ...args) {
  if (typeof this !== 'function') {
    throw new Error('you must use bind with function')
  }
  ctx = ctx || window
  ctx._fn = this
  return function() {
    const res = ctx._fn(...args)
    delete ctx._fn
    return res
  }
}

// ES5 版
Function.prototype.es5bind = function(ctx) {
  if (typeof this !== 'function') {
    throw new Error('you must use bind with function')
  }
  ctx = ctx || window
  ctx._fn = this
  var args = []
  // 做一层缓存,因为下面返回的function中的arguments会和这个arguments冲突
  var fArguments = arguments
  for (var i = 1; i < fArguments.length; i++) {
    args.push("fArguments[" + i + "]")
  }
  var argsStr = args.join(',')
  return function() {
    var res = eval("ctx._fn(" + argsStr + ")")
    delete ctx._fn
    return res
  }
}

console.log(person.calc.es6bind(person2, 1, 2)()) // person2 3
console.log(person.calc.es5bind(person2, 1, 2)()) // person2 3

踩坑

在写call和apply的时候,一时迷了写了下面这种实现方法:

// 错误示范
Function.prototype.callError = function(ctx) {
  ctx = ctx || window
  ctx._fn = this
  var newArr = [];
  for(var i=1; i

结语

内置的call,apply,bind方法要比我写的要复杂且健壮的多。不过自己手动实现这三个方法主要是为了考察这三个函数是否掌握以及函数内部this的指向问题。

你可能感兴趣的:(手写一个 call,apply,bind 吧)