1. call()
语法:
1fun.call(thisArg,arg1,arg2,…)
fun: 表示一个函数
thisArg: this要指向的对象,如果是null 和 undefined,则指向window全局对象;
从arg1开始,都是要给fun传递的参数。
特性:
1fun.call(thisArg,arg1,arg2,…)
会立即调用fun函数;
call 方法将一个函数的对象上下文从初始的上下文改变为由 thisArg 指定的新对象,如果没有提供 thisArg 参数,那么 Window对象被用作 thisArg;
将arg1等参数传递进fun函数中,返回fun函数的返回值。
1function getSum(num1, num2) {
2 console.log(this); // Window
3 return num1 + num2;
4}
5
6const obj = {};
7
8getSum.call(obj, 2, 3); // this指向: obj return: 5
2. apply()
语法:
1fun.apply(thisArg,[arg1,arg2,…])
fun: 表示一个函数
thisArg: this要指向的对象,如果是null 和 undefined,则指向window全局对象;
参数是一个数组。
特性:
1fun.apply(thisArg,[arg1,arg2,…])
会立即调用fun函数;
apply方法将一个函数的对象上下文从初始的上下文改变为由 thisArg 指定的新对象,如果没有提供 thisArg 参数,那么 Window对象被用作 thisArg;
将数组传递进fun函数中,返回fun函数的返回值。
1function getSum(num1, num2) {
2 console.log(this);// Window
3 return num1 + num2;
4}
5
6const obj = {};
7
8getSum.apply(obj, [1, 2]); // this指向: obj return: 3
3. bind()
语法:
1fun.bind(thisArg,[arg1,arg2,…])
fun: 表示一个函数
thisArg: this要指向的对象,如果是null 和 undefined,则指向window全局对象;
从arg1开始,都是要给fun传递的参数。
特性:
1fun.bind(thisArg,arg1,arg2,…)
不会立即调用fun函数,会返回一个新的指定了this的函数;
bind方法将一个函数的对象上下文从初始的上下文改变为由 thisArg 指定的新对象,如果没有提供 thisArg 参数,那么 Window对象被用作 thisArg;
将arg1等参数传递进fun函数中。
1function getSum(num1, num2) {
2 console.log(this); // Window
3 return num1 + num2;
4}
5
6const obj = {};
7const newFun = getSum.bind(obj, 1, 2); // 返回的是一个新的指定了this的函数
8newFun(); // 3
4. call()、apply()和bind()的应用
1. call()
call 常用来继承,因为ES6之前没有extends,用构造函数来模拟继承。
下面例子:
Son通过改变Father构造函数this指向问题,来获取Father里面的属性,实现继承的效果,Son还可以添加自己的额外属性:
1function Father(name, age) {
2 this.name = name;
3 this.age = age;
4}
5
6function Son(name, age, gender) {
7 Father.call(this, name, age);
8 this.gender = gender;
9}
10
11const son = new Son("小明", 24, "男");
12son.name; // 小明
13son.age; // 24
2. apply()
apply 常用于与数组有关的操作,因为传递的参数是数组。
获取数组中的最大值与最小值:
1const arr = [1, 4, 7, -1];
2Math.max.apply(Math, arr); // 7
3Math.min.apply(Math, arr); // -1
数组合并:
1const arr = [1, 2];
2const arr1 = [3];
3Array.prototype.push.apply(arr, arr1); // 3
4conaole.log(arr); // [1, 2, 3]
3. bind()
如果我们想改变某个函数内部的this指向,但又不需要立即调用该函数,此时用bind:
1<body>
2 <button>点击</button>
3 <script>
4 let btn = document.querySelector("button");
5 btn.onclick = function() {
6 this.disabled = true; // 这里this表示btn
7 setTimeout(function() {
8 console.log(this); // 这里this表示Window
9 this.disabled = false; // 所以btn的disabled会一直为true
10 }, 3000)
11 }
12 </script>
13</body>
14-----------------------------------------------------
15<body>
16 <button>点击</button>
17 <script>
18 let btn = document.querySelector("button");
19 btn.onclick = function() {
20 this.disabled = true;
21 setTimeout(function() {
22 console.log(this); // btn
23 this.disabled = false;
24 }.bind(this), 3000) // 这个this是在定时器函数外,所以指向的是btn这个按钮对象。
25 }
26 </script>
27</body>