大家肯定为this指向的问题感到烦恼,接下来让我为大家介绍六种改变this指向的方法吧!
1、在指定位置定义this存为变量
// 在指定位置定义this存为变量// 我们可以自己存一个变量let _this = thisconst obj = {fun(){console.log(_this) //window}}obj.fun()
2.箭头函数
// 箭头函数// 获取按钮,添加点击事件document.querySelector("button").onclick = ()=>{// 在我们普通函数下的事件this指向调用者console.log(this) //window}
3.使用setTimeout
// 使用setTimeout,this指向window// 获取按钮,添加点击事件document.querySelector("button").onclick = function(){setTimeout(function(){console.log(this) //window},1000)}
4.call( )方法改变this指向
作用:调用函数 改变this指向
语法:fun.call(thisArg,arg1,arg2,…)
thisArg:在fun函数运行时指定的this值
arg1,arg2:传递的其他参数
返回值就是函数的返回值,因为它就是调用函数
const obj = {uname: "张三"}function fun(a, b) {//正常情况下指向window// 这里我们使用了call方法改变了this指向,指向了objconsole.log(this) //指向obj {uname : "张三"}// 这里我们传了2个值 1 2console.log(a + b) //3}fun.call(obj, 1, 2)
5.apply( )方法改变this指向
作用:调用函数 改变this指向
语法:fun.apply(thisArg,[argsArray])
thisArg:在fun函数运行时指定的this值
argsArray:传递的值,必须包含在数组里面
返回值就是函数的返回值,因为它就是调用函数
const obj = {uname: "张三"}function fun(a, b) {//正常情况下指向window// 这里我们使用了apply方法改变了this指向,指向了objconsole.log(this) //指向obj {}// 这里我们传了2个值 1 2console.log(a + b) //3}fun.apply(obj, [1, 2])
6、bind( )方法改变this指向(重要)
bind()方法不会调用函数。但是能改变函数内部this指向
语法:fun.bind(thisArg,arg1,arg2,…)
thisArg:在fun函数运行时指定的this值
arg1,arg2:传递的其他参数
返回由指定的this值和初始化参数改造的 原函数拷贝(新函数)
因此当我们只是想改变this指向,并且不想调用这个函数的时候,可以使用 bind ,比如改变定时器内部的this指向
不调用函数:
function fun() {console.log(this) //不打印}fun.bind()
原函数拷贝(新函数)
const obj = {uname: "张三"}function fun() {console.log(this)}// 相当于拷贝// function fun() {// console.log(this)// }fun.bind(obj)
如果想要使用:
const obj = {uname: "张三"}function fun() {console.log(this) //指向obj {uname:"张三"}}// 加()fun.bind(obj)()
感谢大家的阅读,如有不对的地方,可以向我指出,感谢大家!