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

2018-10-26  本文已影响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.

上一篇 下一篇

猜你喜欢

热点阅读