this词法

来源:互联网 发布:香烟能在淘宝销售吗 编辑:程序博客网 时间:2024/06/08 06:45

ES6中this的使用简介:

var obj={id:"awesome",cool:function coolFn() {console.log(this.id);}};var id="not awesome";obj.cool();setTimeout(obj.cool, 100);

直接访问obj.cool会访问对象的方法,而调用setTimeout之后cool()函数丢失了同this之间的绑定。解决问题的方法,最常用的就是var self=this;
var obj={id:"awesome",cool:function coolFn() {var self=this;if(self.count<1){setTimeout(function timer(){self.count++;console.log("awesome?");}, 100);}}};obj.cool();

self只是一个可以通过词法作用域和闭包进行引用的标识符。
通过ES6的箭头函数实现:
var obj={count:0,cool:function coolFn() {if(self.count<1){setTimeout(()={this.count++;console.log("awesome?");}, 100);}}};obj.cool();
var obj={count:0,cool:function coolFn() {if(this.count<1){setTimeout(function timer(){this.count++;console.log("more awesome");}.bind(this),100)}}};obj.cool();
原创粉丝点击