ES6 箭头函数下的this指向

  在javscript中,this 是在函数运行时自动生成的一个内部指针,它指向函数的调用者。

  箭头函数有些不同,它的this是继承而来, 默认指向在定义它时所处的对象(宿主对象),而不是执行时的对象。 

var name = "window"; var test = { name:"demo", // 传统函数 getName1: function(){ console.log(this.name); // demo var that = this; setTimeout(function(){ console.log(this.name); // window console.log(that.name); // demo },500) }, // 箭头函数-作为异步回调 getName2:function(){ setTimeout(()=>{ console.log(this.name) // demo },500) }, // 箭头函数-作为直接执行的方法 getName3:()=>{ console.log(this.name) // window } };

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/zywzgp.html