美文网首页
JavaScript箭头函数的this作用域问题

JavaScript箭头函数的this作用域问题

作者: 旭日丶丶 | 来源:发表于2018-10-26 17:29 被阅读0次
$('#category').children().each(function(){
            console.log(this);

这里的this指向某个child, 为啥这样可以, 却:

$('#category').children().each(()=>{
            console.log(this);

这里的this指向#document, 为啥这样不行呢?

根据:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions#No_separate_this

箭头函数没有this
this取决于该函数被调用的位置


代码1这里的this在该function内 , 由于each是个callback, 调用function()的地方的
的enclosure里有一个element, 所以this指向的是'那个'element.

代码2里的箭头函数没有this, 所以this将会寻找它的上一个函数each()被调用的作用域的this, #document, 所以this自然指向#document.

相关文章

网友评论

      本文标题:JavaScript箭头函数的this作用域问题

      本文链接:https://www.haomeiwen.com/subject/nkjltqtx.html