call的模拟实现

call:

call()方法在使用一个指定的 this 值和若干个指定的参数值的前提下调用某个函数或方法

举例:

var foo = {
    value: 1
};

function bar() {
    console.log(this.value);
}
bar.call(foo); // 1

根据上面的案例,我们可以注意到两点

  • call改变了this指向,指向了foo
  • bar函数执行了

模拟实现第一步

看到上面的效果,我们该如何实现呢?
首先我们可以将代码改写成以下形式

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

改造过后我们可以看到此时的this也是指向foo的,但是这样却是给foo对象添加了一个属性bar的函数,这样是不合适的,不过我们可以使用delete方法将其删除,因此步骤可以分为以下三步:

  • 将函数设为对象的属性
  • 执行该函数
  • 删除该函数

以上三个步骤就可以写做:

注意:因为是在对象中添加属性,fn属性名字可以随便写,反正也要删除
  foo.fn = bar
  foo.fn()
  delete foo.fn

根据以上思路实现第一版:

Function.prototype.call2 = function (context) {
    // this谁调用指向谁,此时是函数bar调用call2,因为this指向bar
    context.fn = this
    context.fn()
    delete context.fn
}
var foo = {
    value: 1
}
function bar() {
    console.log(this.value) // 1
}
bar.call2(foo)

模拟实现第二步

我们知道call方法还可以给定参数,可以看如下案例:

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

但是我们要知道参数传递是不固定的,因此我们可以使用在argument中取值,取出我们传递的第二个参数到最后一个参数,任何添加到一个数组中,实现代码如下

var arg = []
for(var i = 1; i < argument.length; i++){
    args.push('arguments[' + i + ']');
}
注意:arguments是一个伪数组,因此要用for循环

解决了传递参数不定长的问题,那么参数放到需要执行的函数参数中应该如何实现呢?

context.fn(arg.join(''))
这种方法是肯定不行的

我们可以通过ES3中的eval来实现,这样就可以实现函数参数传递以及调用了

eval('context.fn(' + args +')')

所以第二版就实现如下

Function.prototype.call2 = function (context) {
    context.fn = this
    var args = []
    for (var i = 1; i < arguments.length; i++) {
        args.push('arguments[' + i + ']')
    }
    eval('context.fn(' + args + ')')
    delete context.fn
}

模拟实现第三步

  • this参数可以传null,当为null的时候,视为指向window
var value = 1
function bar() {
    console.log(this.value)
}
  • 函数是有返回值的
var obj = {
    value: 1
}
function bar(name, age) {
    return {
      value: this.value,
      name,
      age
    }
}
console.log(bar.call(obj, '张三', 18))

不过这个很好实现,直接上最终版

Function.prototype.call2 = function (context) {
    var context = context || window
    context.fn = this
    var args = []
    for (var i = 1; i < arguments.length; i++) {
        args.push('arguments[' + i + ']')
    }
    var result = eval('context.fn(' + args + ')')
    delete fn
    return result
}
var obj = {
    value: 1
}
function bar(name, age) {
    return {
      value: this.value,
      name,
      age
    }
}
console.log(bar.call2(obj, '张三', 18))

也可以使用ES6的语法实现

Function.prototype.call2 = function (context, ...args) {
    context = context || window
    // Symbol为了防止有相同的函数名
    let fn = Symbol()
    context.fn = this
    const 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)
}

主要参考:https://github.com/mqyqingfen...

评论

暂无评论