四、函数绑定

四、函数绑定

4.1 call apply bind

ES5为函数拓展了一个bind方法

作用就是:

为函数绑定作用域(执行函数,改变作用域,传递参数)

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
// call 方法:
// 执行函数,并改变函数的this指向
// 第一个参数就是要改变的this指向,从第二个参数开始都是原函数所需参数

// apply 方法:
// 执行函数,并改变函数的this指向
// 第一个参数就是要改变的this指向,第二个参数是一个数组,数组中的每一项都是原函数所需参数

// bind 方法:
// bind 方法与 call 方法类似,都是执行函数,并改变this指向
// 第一个参数就是要改变的this指向,从第二个参数开始都是原函数所需参数
// bind 与 call 和 apply 之间的区别:
// call apply 调用即执行
// bind 调用不会执行,而是返回一个新的方法


// 定义函数
function fun(){
console.log(this, arguments);
}
// 函数自执行
fun(); // this 指向 window 不传递参数时 arguments为空

// 使用call 方法
fun.call(document, 1, 2); // this 指向document, arguments有两个参数: 1 2

// 使用 apply 方法
fun.apply(document.body, [3, 4]); // this 指向 body arguments有两个参数:3 4

// 使用 bind 方法
// fun.bind(document.body, 5, 6); // bind 调用不会执行,而是返回一个新的方法
var result = fun.bind(document.body, 5, 6);
result(); // this 指向 body arguments有两个参数:5 6

Ulq1xA.png

4.2 bind方法的实现

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
function fun(){
console.log(this, arguments);
}

// 取消bind方法
// 既然用fun()调用方法,说明是在构造函数Function的原型上
Function.prototype.bind = null;
// fun.bind(); // 报错 不能使用了 Uncaught TypeError: fun.bind is not a function
// 实现bind方法
Function.prototype.bind = function(target){
// 获取剩余的参数
var arg = [].slice.call(arguments, 1);
// 缓存 this
var me = this;
// 返回新的方法
return function(){
// 获取剩余的参数
var addArg = [].slice.call(arguments);
// 调用数组合并方法 将下面的参数合并到上面
var result = arg.concat(addArg);
console.log(result);
me.apply(target, result);
}
}

var result = fun.bind(document, 6, 7);
// result执行的时候 this已被改变,并执行其中的参数
result(1, 2);

Ulq8KI.png

点击查看

本文标题:四、函数绑定

文章作者:Mango

发布时间:2020年07月14日 - 12:56:58

最后更新:2020年07月14日 - 13:27:10

原始链接:https://mango185.github.io/post/cc5cc6c3.html

许可协议: 署名-非商业性使用-禁止演绎 4.0 国际 转载请保留原文链接及作者。

-------------------本文结束 感谢您的阅读-------------------