How to initialize an object property based on the values of other properties using a function?

61 Views Asked by At
  1. I want to create an object literal.
  2. 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.
  3. 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.

1

There are 1 best solutions below

0
JeanJacquesGourdin On

This is due to the closures differences between functions and arrow functions.

  • arrow function has its parent context for "this"
  • function has its own context for "this"

Examples :

const obj1 = {
  a: 1,
  b:2, 
  c:()=>{console.log(this)} //context: stackoverflow page
}

const obj2 = {
  a: 1,
  b:2, 
  c:function c(someArg){console.log(this)} //context obj2
}

const obj3 = {
  a: 1,
  b:2, 
  c:(someArg)=>{console.log(obj3)} //obj3 =)
}

obj1.c()
obj2.c()
obj3.c()