使用模拟实现的方式探究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. 删除这个函数

下面就试着去实现一下:

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', '18')
// black
// 18
// 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 // this 也就是调用call的函数
    var args = [...arguments].slice(1)
    var result = context.fn(...args)
    delete context.fn()
    return result
}
var value = 1
function bar() {
    console.log(this.value)
}
bar.call2()

apply

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

Function.prototype.apply2 = function(context) {
    var context = context || window
    context.fn = this // this 也就是调用apply的函数
    var result
    // 判断是否有第二个参数
    if(arguments[1]) {
        result = context.fn(...arguments[1])
    } else {
        result = context.fn()
    }
    delete context.fn()
    return result
}

var foo = {
    value: 1
}
function bar(name, age) {
    console.log(name)
    console.log(age)
    console.log(this.value);
}
bar.apply2(foo, ['black', '18']) // black 18 1

hu970804
63 声望4 粉丝