call、apply和bind的原理

使用模拟实现的方式探究call和apply的原理
call

作用:

call() 方法就是使用一个指定this值和若干个指定参数值的前提下调用摸个函数或方法。`

var foo = {
	value: 1
}
function bar () {
	console.log(this.value)
}
// 如果不对this进行绑定执行bar() 会返回undefined
bar.call(foo) // 1

也就是说call()改变了this的指向,指向了foo

下面进行一下模拟实现

试想当调用call的时候,也就是类似于

var foo = {
	value: 1,
	bar: function(){
		console.log(this.value)
	}
}
foo.bar() //1

这样就把this指向到foo上了,但是会给foo对象加了一个属性,有些瑕疵,不过不要紧,执行完删除这个属性就可以完美实现了。

也就是说步骤可以是这样

  1. 将函数设为对象的属性
  2. 执行这个函数
  3. 删除这个函数

下面就试着去实现一下:

// context是指this指向的对象,如上文的foo
Function.prototype.call2 = function (context) {
	context.fn = this //this 也就是调用call的函数,将函数设为对象的属性
	var result = context.fn() // 执行这个函数
	delete context.fn // 删除这个函数
	return result
}
var foo = {
	value: 1
}
function bar () {
	console.log(this.value)
}
bar.call2(foo) // 1

但是这样有一个小缺陷就是call()不仅能指定this到函数,还能传入给定参数执行函数,比如:

var foo = {
	value: 1
}
function bar(name, age) {
	console.log(name)
	console.log(age)
	console.log(this.value)
}
bar.call(foo, 'black', 17)
// black
// 17
// 1

特别要注意的一点是,传入的参数的数量是不确定的,所以我们要使用arguments对象,去除除去第一个之外的参数,放到一个数组中:

Function.prototype.call2 = function (context) {
	context.fn = this //this 也就是调用call的函数,将函数设为对象的属性
	var args = [...arguments].slice(1)
	var result = context.fn(...args) // 执行这个函数
	delete context.fn // 删除这个函数
	return result
}
var foo = {
    value: 1
}
function bar(name, age) {
    console.log(name)
    console.log(age)
    console.log(this.value);
}
bar.call2(foo, 'black', '18') // black 18 1

还有一点需要注意的是,如果不传入参数,默认指向window,所以最终版代码:

Function.prototype.call2 = function(context) {
	var context = context || window
	context.fn = this
	var args = [...arguments].slice(1)
	var result = context.fn(...args)
	delete context.fn
	return result
}
apply

apply方法和call方法的实现类似,只不过如果有参数,以数组形式进行传递,直接上代码

Function.prototype.apply2 = function(context) {
	var context = context || window
	context.fn = this
	var args = arguments[1]
	var result = context.fn(...args)
	delete context.fn
	return result
}
bind

bind方法的主要作用就是将函数绑定至某个对象,bind方法会创建一个函数,函数体内this对象的值会被绑定到传入bind() 函数的值。

Function.prototype.bind2 = function(context) {
	var self = this
	var args = [...arguments].slice(1)
	return function () {
		return self.apply2(context, args)
		// 或者
		//return self.apply(context, args)
	}
}
call、apply和bind的区别

共同点:

都可以改变函数执行的上下文环境;

不同点:

bind: 不立即执行函数,一般用在异步调用和事件; call/apply: 立即执行函数。

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值