this指向问题以及改变this指向的三种方法

it2024-07-23  40

this指向问题:

一般情况下this的最终指向的是哪个调用它的对象

全局作用域或者普通函数中this指向全局对象window (注意定时器里面的this指向window) console.log(this); function fn(){ console.log(this); } window.fun(); //定时器函数 setTimeout(function(){ console.log(this); },1000); 方法调用中谁调用this指向谁 var o={ sayHi:function(){ console.log(this);//this指向的是o这个对象 } } o.sayHi(); 构造函数中this指向构造函数的实例对象,原型对象里面的this指向的也是构造函数的实例对象 function Fun(){ console.log(this);//this指向的是fun实例对象 } Fun.prototype.sing=function(){ } var fun=new Fun(); 绑定事件函数this指向的是函数的调用者btn var btn=document.querySelector('button'); btn.onclick=funcion(){ console.log(this);//this指向的是btn这个按钮对象 }; btn.addEventListener('click',function(){ console.log(this);//this指向的是btn这个按钮对象 }); 立即执行函数this指向window (function(){ console.log(this); })()

改变函数内部this指向三种方法:

call()

fun.call(thisArg,arg1,arg2,…)

可以调用函数可以改变函数内部this指向call主要作用可以实现继承 var o={ name:'andy' } function fn(a,b){ console.log(this); console.log(a+b); } //调用函数 改变this指向 fn.call(o,1,2); //实现继承 function Father(uname,age,sex){ this.uname=uname; this.age=age; this.sex=sex; } function Son(uname,age,sex){ Father.call(this,uname,age,sex); } var son=new Son('小明',18,'男'); console.log(son); apply()

fun.apply(thisArg,[argsArray])

可以调用函数可以改变函数内部的this指向它的参数必须是数组(伪数组) var o={ name:'andy' }; function fn(arr){ console.log(this); console.log(arr);//'sy' } //改变this指向 fn.apply(o,['sy']); //利用apply借助数学内置对象求最大值和最小值 var arr=[1,66,99,5]; var max=Math.max.apply(Math,arr); var min=Math.min.apply(Math,arr); console.log(max,min);//99 1 bind()

fun.bind(thisArg,arg1,arg2,…)

不会调用函数可以改变函数内部this指向返回的是原函数改变this之后产生的新函数 var o={ name:'andy' }; function fn(){ console.log(this); } //fn.bind(o);绑定方法但不执行 var f=fn.bind(o); f(); 如果有的函数我们不需要立即调用,但是又想改变this指向此时用bind var btn=document.querySelector('button'); btn.onclick=function(){ this.disabled=true;//this指向btn这个按钮 //var that=this; setTimeout(function(){ //that.disabled=false; this.disabled=false;//this指向的是window }.bind(this),3000)//这个this指向的是btn这个对象 }
最新回复(0)