call、apply、bind作用、实现及详解

37 篇文章 0 订阅
27 篇文章 0 订阅

call、apply、bind作用、实现及详解

它们有什么不同?怎么用?

  • call 接收多个参数,第一个为函数上下文也就是this.后边参数为函数本身的参数
let obj ={
	name:'小猪头'
}

function printName(firstName, lastName,flag){
	console.log(this)
	console.log(`第一个名字${firstName} | ${this.name} | 第二个名字${lastName} flag:${flag}`)
}

printName.call(obj,'豆豆','甜甜')

这里的this是没有绑定之前 所以是window
在这里插入图片描述call 之后
在这里插入图片描述

apply

  • apply接收两个参数,第一个参数为函数上下文this,第二个参数为函数参数只不过是通过一个数组的形式传入的。
 printName.apply(obj,['豆豆','甜甜','甜豆'])
  • apply的一些其他巧妙用法
    (一)Math.max 可以实现得到数组中最大的一项
    因为Math.max 参数里面不支持Math.max([param1,param2]) 也就是数组

但是它支持Math.max(param1,param2,param3…),所以可以根据刚才apply的那个特点来解决 var max=Math.max.apply(null,array),这样轻易的可以得到一个数组中最大的一项(apply会将一个数组装换为一个参数接一个参数的传递给方法)

     这块在调用的时候第一个参数给了一个null,这个是因为没有对象去调用这个方法,我只需要用这个方法帮我运算,得到返回的结果就行,.所以直接传递了一个null过去

同理: Math.min 可以实现得到数组中最小的一项
同样和 max是一个思想 var min=Math.min.apply(null,array);
(二) Array.prototype.push 可以实现两个数组合并
在这里插入图片描述- 实现call
首先看一个例子

let Person = {
	name:'Tom',
	say(){
		console.log(this)
		console.log(`我是${this.name}`)
	}
}

let PersonSelf = {
	name :'Tony'
}
Person.say.call(PersonSelf ) //我叫Tom

实现call

Function.prototype.myCall = function(context) {
	//context就是demo中的Person1
	if(typeof this !== 'function'){
		throw  new TypeError('Error')
	}
	// 必须此时调用MyCall的函数是say方法,
	//那么我们只需要在context上扩展一个say方法指向调用MyCall的say方法这样this
	context  = context || window//首先 context 为可选参数,如果不传的话默认上下文为 window
	//Mycall里边的this就是我们虚拟的say方法
	context.fn = this
	// 处理参数 去除第一个参数this 其它传入fn函数
	[...xxx]把类数组变成数组,arguments为类数组 slice返回一个新数组
	const args = [...arguments].slice(1)
	const result = context.fn(...args)
	//然后调用函数并将对象上的函数删除
	delete context.fn
	return result
	
}
  • apply
Function.prototype.myApply = function(context) {
  if (typeof this !== 'function') {
    throw new TypeError('Error')
  }
  context = context || window
  context.fn = this
  let result
  // 处理参数和 call 有区别
  if (arguments[1]) {
    result = context.fn(...arguments[1])
  } else {
    result = context.fn()
  }
  delete context.fn
  return result
}
  • bind
Function.prototype.myBind = function (context) {
  if (typeof this !== 'function') {
    throw new TypeError('Error')
  }
  const _this = this
  const args = [...arguments].slice(1)
  // 返回一个函数
  return function F() {
    // 因为返回了一个函数,我们可以 new F(),所以需要判断
    if (this instanceof F) {
      return new _this(...args, ...arguments)
    }
    return _this.apply(context, args.concat(...arguments))
  }
}
  • bind 返回了一个函数,对于函数来说有两种方式调用,一种是直接调用,一种是通过 new 的方式,我们先来说直接调用的方式
  • 对于直接调用来说,这里选择了 apply 的方式实现,但是对于参数需要注意以下情况:因为 bind 可以实现类似这样的代码 f.bind(obj, 1)(2),所以我们需要将两边的参数拼接起来,于是就有了这样的实现 args.concat(…arguments)
  • 最后来说通过 new 的方式,在之前的章节中我们学习过如何判断 this,对于 new 的情况来说,不会被任何方式改变 this,所以对于这种情况我们需要忽略传入的 this
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值