- I want to create an object literal.
- In this object I want to have a property which will be a function that produces a value depending on the value of other properties of this same object and one argument.
- I want to know the reason behind why the first 2 scenarios mentioned below do not work but the third one does.
const obj1 = {
a: 1,
b:2,
c:(someArg)=>someArg*this.a + this.b
} // Does not work after Exporting to a different file
const obj2 = {
a: 1,
b:2,
c:function c(someArg){ return someArg*this.a + this.b }
} // Does not work after exporting to a different file i.e export const obj2 = {..}
const obj3 = {
a: 1,
b:2,
c:(someArg)=>{ return someArg*obj3.a + obj3.b }
} // Works
console.log(obj1.c(1))
console.log(obj2.c(1))
console.log(obj3.c(1))
In the above snippet, obj2 is working for some reason but when I try to build such an object literal and export it to a diferent file in my react project it does not work.
This is due to the closures differences between functions and arrow functions.
Examples :