使用模拟实现的方式探究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对象加了一个属性,有些瑕疵,不过不要紧,执行完删除这个属性就可以完美实现了。
也就是说步骤可以是这样
- 将函数设为对象的属性
- 执行这个函数
- 删除这个函数
下面就试着去实现一下:
// 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: 立即执行函数。