0

I'm new to javascript and having trouble understanding the difference between arrow function and normal function when including this keyword, here is the example I read from MDN:

var obj = { // does not create a new scope
  i: 10,
  b: () => console.log(this.i, this),
  c: function() {
    console.log(this.i, this);
  }
}

obj.b(); // prints undefined, Window {...} (or the global object)
obj.c(); // prints 10, Object {...}

In this example arrow function b() can not access i attribute in the object because it references the window

var obj = {
    count : 10,
    doSomethingLater : function(){ // of course, arrow functions are not suited for methods
        setTimeout( () => { // since the arrow function was created within the "obj", it assumes the object's "this"
            this.count++;
            console.log(this.count);
        }, 300);
    }
}

obj.doSomethingLater(); //log 11 on the console

However, in the second example, code within the arrow function can access the count attribute. Both functions are defined within the object but only the second function can access the object's attribute, could someone give me some hints why is that? Thanks in advance!

xxddd_69
  • 83
  • 1
  • 7
  • "*Both functions are defined within the object*" - no. The `function` expression is defined in the top-level scope, whereas the arrow function is defined **within the outer `function`**. – Bergi Jul 13 '21 at 01:54
  • thanks for your answer, so the function b() is defined within window scope and c() is top-level scope? – xxddd_69 Jul 13 '21 at 02:39
  • I was talking about the second example. In the first example, the `b` and `c` functions are both defined in the same scope. – Bergi Jul 13 '21 at 03:00
  • I was confused why b() can not access property i while c() can access i – xxddd_69 Jul 13 '21 at 03:08
  • That's because of the different `this` values in your example calls. Did you read the explanation in the duplicates linked by @CertainPerformance? – Bergi Jul 13 '21 at 03:15

0 Answers0