当前位置: 首页 > 后端技术 > Node.js

这指向问题

时间:2023-04-03 18:09:06 Node.js

不同开发方式环境下全局环境this指向的提示:this的指向是在代码运行时动态绑定的。浏览器中全局环境的this指向window//testconsole.log(this);//windownode中全局环境的this指向global//testconsole.log(this)//global"usestrict"globalinstrictmode环境的this指向undefined"usestrict"//testconsole.log(this)//undefined谁调用this就指向谁在全局环境中函数调用自己,函数中的this指向全局环境中this指向的对象注:全局环境中调用自身的函数是类似于在全局环境中被this指向的对象调用(eg:window.F())letname="Jason"functiongetName(){console.log(this.name);}1.浏览getName()在浏览器中//Jason,this->window//类似于window.getName()3。node环境中的getName()//Jason,this->global//类似于global.getName()3。strict"usestrict"getName()模式下//undefined,this->undefined//类似于undefined.getName()调用对象中的方法时,this指向调用它的对象letuser={name:"Jason",getName:function(){console.log(this);console.log(this.name);},obj:{age:23,getAge:function(){console.log(this);控制台日志(这个年龄);}}}//测试Tryuser.getName()//userJason,this->useruser.obj.getAge()//obj23,this->obj构造函数中的this指向构造函数User(name,age)的实例对象{这个.name=名字;this.age=age;}User.prototype.getUser=function(){console.log(this)}//testletuser=newUser("Jason",23)user.getUser();//this指向构造函数实例,this->usersetTimeout,setInterval中的this指向全局中的thisletF=()=>{setTimeout(function(){console.log(this)},2000)}//testF();//window,this->windowClass中的this指向类实例的对象classUser{constructor(name,age){this.name=name;这个。年龄=年龄;}getUser(){console.log(this.name);控制台日志(这个年龄);控制台日志(这个);}}//testletuser=newUser("Jason",23);user.getUser()//Jason23,this->user箭头函数中没有this,如果箭头函数中使用了this,则this指向this,依赖于外部对象或函数setTimeout(()=>{console.log(this);},3000)//this->windoweow,箭头函数中的this指针依赖于setTimeout的this指向