Iwen's blog Iwen's blog
首页
  • 前端文章

    • JavaScript
    • Vue
  • 学习笔记

    • 《JavaScript教程》笔记
    • 《JavaScript高级程序设计》笔记
    • 《ES6 教程》笔记
    • 《Vue》笔记
    • 《TypeScript 从零实现 axios》
    • 小程序笔记
  • HTML
  • CSS
  • 技术文档
  • GitHub技巧
  • Nodejs
  • 博客搭建
  • Linux
  • 学习
  • 面试
  • 心情杂货
  • 友情链接
  • 网站
  • 资源
  • Vue资源
  • 分类
  • 标签
  • 归档
复盘
关于

Iwen

不摸鱼的哥哥
首页
  • 前端文章

    • JavaScript
    • Vue
  • 学习笔记

    • 《JavaScript教程》笔记
    • 《JavaScript高级程序设计》笔记
    • 《ES6 教程》笔记
    • 《Vue》笔记
    • 《TypeScript 从零实现 axios》
    • 小程序笔记
  • HTML
  • CSS
  • 技术文档
  • GitHub技巧
  • Nodejs
  • 博客搭建
  • Linux
  • 学习
  • 面试
  • 心情杂货
  • 友情链接
  • 网站
  • 资源
  • Vue资源
  • 分类
  • 标签
  • 归档
复盘
关于
  • Vue

  • Vue进阶

  • CSS

  • ES6

  • Base

  • Core

  • Array

  • Object

  • String

  • Async

  • Browser

  • Http

  • 性能优化

  • 正则

  • 经典总结

  • 设计模式

  • 数据结构

  • 算法

  • 手写

    • call、apply
      • 模拟实现第一步
      • 模拟实现第二步
      • 模拟实现第三步
      • apply的模拟实现
    • 实现bind函数
    • instanceOf
    • new 原理及模拟实现
    • 防抖、节流
    • 发布订阅模式
    • 深拷贝
    • Promise A+
    • Promise 进阶
    • Array-prototype-map
    • Array-prototype-filter
    • Array-prototype-reduce
    • 并发请求
    • 继承
    • JSON 字符串
  • TypeScript

  • 复盘
  • 手写
Mr.w
2020-11-29

call、apply

# call、apply

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

举个例子:

var foo = {
    value: 1
};

function bar() {
    console.log(this.value);
}

bar.call(foo); // 1

1
2
3
4
5
6
7
8
9
10

注意两点:

  1. call 改变了 this 的指向,指向到 foo
  2. bar 函数执行了

# 模拟实现第一步

那么我们该怎么模拟实现这两个效果呢?

试想当调用 call 的时候,把 foo 对象改造成如下:

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

foo.bar(); // 1
1
2
3
4
5
6
7
8
// 第一版
Function.prototype.call = function(context) {
    /**
     * context => 指向对象(第一个参数)
     * this => 调用的函数(调用call的函数)
     */
    context.fn = this;
    context.fn();
    delete context.fn;
}

// 测试一下
var foo = {
    value: 1
};

function bar() {
    console.log(this.value);
}

bar.call(foo); // 1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21

# 模拟实现第二步

最一开始也讲了,call 函数还能给定参数执行函数。举个例子:

var foo = {
    value: 1
};

function bar(name, age) {
    console.log(name, age, this.value)
}

bar.call(foo, 'Libai', 18);
// Libai 18 1
1
2
3
4
5
6
7
8
9
10

注意:传入的参数并不确定,这可咋办?

不急,我们可以从 Arguments 对象中取值,取出第二个到最后一个参数,然后放到一个数组里。

比如这样:

// 以上个例子为例,此时的arguments为:
// arguments = {
//      0: foo,
//      1: 'Libai',
//      2: 18,
//      length: 3
// }
// 因为arguments是类数组对象,所以可以用for循环, 第一个值为this指向, 所以跳过
var args = [];
for(var i = 1; i < arguments.length; i++) {
    args.push('arguments[' + i + ']');
}

// 执行后 args为 ["arguments[1]", "arguments[2]", "arguments[3]"]
1
2
3
4
5
6
7
8
9
10
11
12
13
14

也许有人想到用 ES6 的方法,不过 call 是 ES3 的方法,我们为了模拟实现一个 ES3 的方法,要用到ES6的方法,好像……,嗯,也可以啦。但是我们这次用 eval 方法拼成一个函数,类似于这样:

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

这里 args 会自动调用 Array.toString() 这个方法。

所以我们的第二版克服了两个大问题,代码如下:

// 第二版
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 +')');
    // context.fn(arguments[1],arguments[2])

    delete context.fn;
}

// 测试一下
var foo = {
    value: 1
};

function bar(name, age) {
    console.log(name, age, this.value)
}

bar.call2(foo, 'Libai', 18);
// Libai 18 1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24

(๑•̀ㅂ•́)و✧

# 模拟实现第三步

1.this 参数可以传 null,当为 null 的时候,视为指向 window

举个例子:

var value = 1;

function bar() {
    console.log(this.value);
}

bar.call(null); // 1
1
2
3
4
5
6
7

虽然这个例子本身不使用 call,结果依然一样。

2.函数是可以有返回值的!

var obj = {
    value: 1
}

function bar(name, age) {
    return {
        value: this.value,
        name: name,
        age: age
    }
}

console.log(bar.call(obj, 'Libai', 18));
// {
//    value: 1,
//    name: 'Libai',
//    age: 18
// }
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18

不过都很好解决,让我们直接看第三版也就是最后一版的代码:

Function.prototype.call = function (context) {
    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 context.fn
    return result;
}

// test
var value = 2;
var foo = {
    value: 1
}
function bar(name, age){
    return {
        value: this.value,
        name: name,
        age: age
    }
}

bar.call2(null) // 2

console.log(bar.call2(foo, 'Libai', '18'))
// {
//    value: 1,
//    name: 'Libai',
//    age: 18
// }

// es6
Function.prototype.call = function (context, ...args) {
    context = context || window;
    context.fn = this;

    let result = context.fn(...args);

    delete context.fn
    return result;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47

到此,我们完成了 call 的模拟实现,给自己一个赞 b( ̄▽ ̄)d

# apply的模拟实现

apply 的实现跟 call 类似,在这里直接给代码,代码来自于知乎 @郑航的实现:

Function.prototype.apply = function (context, arr) {
    var context = Object(context) || window;
    context.fn = this;

    var result;
    // 判断是否存在第二个参数
    if (!arr) {
        result = context.fn();
    }
    else {
        var args = [];
        for (var i = 0; i < arr.length; i++) {
            args.push('arr[' + i + ']');
        }
        result = eval('context.fn(' + args + ')')
    }

    delete context.fn;
    return result;
}

// es6
Function.prototype.apply = function (context, args) {
    context = context || window;
    context.fn = this;

    let result = context.fn(...args);
    
    delete context.fn
    return result;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31

参考大佬们:

  • JavaScript深入之call和apply的模拟实现 (opens new window)
  • 深度解析 call 和 apply 原理、使用场景及实现 (opens new window)
链表
实现bind函数

← 链表 实现bind函数→

最近更新
01
flex布局页面自适应滚动条问题
12-28
02
前后端分离开发请求接口跨域如何携带cookie的问题
12-28
03
怎么实现div长宽比固定width-height4比3
12-28
更多文章>
Theme by Vdoing | Copyright © 2017-2022 Iwen | MIT License
  • 跟随系统
  • 浅色模式
  • 深色模式
  • 阅读模式