2

how can I get access my "count" object inside the arrow function ??

const myCounter = {
    count: 0,
    increment: () => {
        this.count += 1   
        //i know that the arrow functions can't work with "this." ... so how we get access count ??
    },
    currentValue: () => {
        return this.count
    }
}
Kresimir
  • 777
  • 5
  • 20

1 Answers1

1

An arrow function expression has a shorter syntax than a function expression and does not have its own this, arguments, super, or new.target. These function expressions are best suited for non-method functions, and they cannot be used as constructors.

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

So, if you need to use this, define the methods using the function keyword:

const myCounter = {
    count: 0,
    increment: function () {
        this.count += 1;
    },
    currentValue: function () {
        return this.count;
    }
}
Kresimir
  • 777
  • 5
  • 20
  • so I can't use the arrow function in this case ?? ... I just want to learn – Djämel Mãhrouğuı Dec 23 '18 at 14:34
  • No, arrow functions do not well for methods in objects, because they don't have their own `this`. Check out the link in my answer, it explains everything in great detail. If something is unclear, ask and I'll do my best to answer. – Kresimir Dec 23 '18 at 16:34