定义
改变函数执行时上下文,改变this的指向
改变 this 指向
call 和 apply是立即执行,而bind会返回一个函数
1 | let obj = {
|
2 | name: "张三",
|
3 | }
|
4 |
|
5 | function Child(name) {
|
6 | this.name = name
|
7 | }
|
8 |
|
9 | Child.prototype = {
|
10 | constructor: Child,
|
11 | say: function () {
|
12 | console.log(this.name);
|
13 | }
|
14 | }
|
15 |
|
16 | var child = new Child('李四')
|
17 | child.say()
|
18 |
|
19 | child.say.call(obj)
|
20 | child.say.apply(obj)
|
21 | let bind = child.say.bind(obj)
|
22 | bind()
|
call 和 apply 的区别
它们第一个参数都是用来改变this,区别主要在于第二个参数上。call 是参数列表的形式,而apply接受一个数组。
1 | console.log(Math.max.call(null,1,2,3,4,5));
|
2 | console.log(Math.max.apply(null,arr));
|
应用
将类数组转化为数组
1 | let div = document.getElementsByTagName('div')
|
2 | console.log(div);
|
3 |
|
4 | let arr = Array.prototype.slice.call(div)
|
5 | console.log(arr);
|
1 | function fn(){
|
2 | return Array.prototype.slice.call(arguments)
|
3 | }
|
4 |
|
5 | console.log(fn(1,2,3,4));
|
数组拼接
1 | let arr1 = [1,2,3]
|
2 | let arr2 = [4,5,6]
|
3 |
|
4 | Array.prototype.push.apply(arr1, arr2);
|
5 | console.log(arr1);
|