1、 this 的指向是当调用函数时确定的,调用的方式不同,this 的指向也就不同。
1.1 this 一般是指向调用者。
| 函数类型 | this 的指向 |
| 普通函数 | Window |
| 定时器函数 | Window |
| 立即执行函数 | Window |
| 对象方法 | 对象本身 |
| 构造函数(原型对象) | 实例对象 |
2、改变函数内部 this 指向
常用的 3 种方法:call()、apply()和bind()。
2.1 call('this 指向的对象','参数1','参数2')
let obj = { name:'Coder Yarn';};function fn(a,b){ console.log(this); console.log(a + b);};fn.call(obj,2,5);//输出结果{name:'Coder Yarn';}7function Father(username,age,sex){ this.username = username; this.age = age; this.sex = sex;};function Son(username,age,sex){ Father.call(this,username,age,sex);};//实例化对象let son = new Son('Coder Yarn','22','男');console.log(son);//结果输出Coder Yarn22男
2.2 apply(thisArg, [argArray])
thisArg: 在 fun 函数运行时指定的 this 值。 argArray:传递的参数,必须包含在数组中
返回值就是函数的返回值,因为他就是调用函数
//通过数学的内置方法求数组的最大值//let arr = [3,55,88,7,9];let max = Math.max.apply(Math,arr); //this 指向 Math 实例console.log(max);//输出结果88
2.3 bind(thisArg,arg1,arg2,....)
thisArg:在 fun() 函数运行时指定的 this 值。 arg1,arg2:传递其他参数
返回由指定的 this 值和初始化参数改造的原函数拷贝,即返回一个新的函数
let obj = { name:'Coder Yarn';};function fun(a,b){ console.log(this); console.log(a + b);};let newfun = fun.bind(obj,2,3);newfun();//输出结果{name:'Coder Yarn';}5
//获取 button 按钮元素let btn = document.querySelector('button');btn.onclick = function(){ this.disabled = true; //this 指向的是 btn //计时器 setTimeout(function(){ this.disabled = false; //没有 bind() 方法时 this 的指向是 window ,使用 bind() 方法后 this 指向 btn }.bind(this),1000);};//输出结果自己去实现一下吧