js中的this指向问题及解决方案
2016-10-16 00:16
781 查看
<span style="font-size:18px;">//this的指向问题简介 //改写成class class obj{ constructor(){ this.name = "zxh"; //必须要有this,this为当前的对象 this.age = 12; } say(){ console.log(this.name+" "+this.age); } } class animals{ constructor(){ this.name = "gou"; this.age = 23; } says(say){ setTimeout(function(){ console.debug(this.name+" "+this.age+" "+say); //这里的this指向存在问题,:undefined undefined hahah },100); } } var ss = new animals(); ss.says("hahah"); //解决这的bug问题 //1、第一种方式,将this修改为animals,因为当前的this定义时是在当前对象,但是使用是在窗体对象,也就是全局对象中,所以this指向的不同 class animals{ constructor(){ this.name = "gou"; this.age = 23; } says(say){ setTimeout(function(){ console.debug(animals.name+" "+animals.age+" "+say); },100); } } var ss = new animals(); ss.says("hahah"); //2、第二种方式,通过将copy this 实现指针指向当前的对象 class animals{ constructor(){ this.name = "gou"; this.age = 23; } says(say){ let thisCopy = this; setTimeout(function(){ console.debug(thisCopy.name+" "+thisCopy.age+" "+say); },100); } } var ss = new animals(); ss.says("hahah"); //3、第三种方式,通过bind(this)实现 class animals{ constructor(){ this.name = "gou"; this.age = 23; } says(say){ let thisCopy = this; setTimeout(function(){ console.debug(this.name+" "+this.age+" "+say); }.bind(this),100); } } var ss = new animals(); ss.says("hahah"); //4、第四种,通过es6 arrow实现,因为箭头函数时定义函数时和执行函数时都是指向的当前对象 class animals{ constructor(){ this.name = "zxh"; this.age = 21; } says(say){ setTimeout(()=>{ console.log(this.name+" "+this.age+" "+say); },100); } } var ss = new animals(); ss.says("hahah");</span>
相关文章推荐
- js中this指向问题
- js中this指向问题实例详解
- js中this的指向问题
- 小白也能彻底理解js中this的指向问题
- js中this指向问题
- JS中setTimeout的作用域以及this的指向问题
- JS中的this指向问题以及apply、call、bind的使用
- js 深入理解this指向问题
- Js中的this指向问题(2)
- js中this指向问题
- Atitit.js this错误指向window的解决方案
- 理解js中this的指向问题
- 彻底理解JS中This指向问题
- JS中各种this指向问题
- 解决js绑定事件this指向发生改变的问题
- Atitit.js this错误指向window的解决方案
- 如何理解JS中的this指向问题
- 详解JS中定时器setInterval和setTImeout的this指向问题
- js中的this指向问题
- 关于JS中for循环时,作用域问题和this指针指向的总结