0

Example of what i'm trying to achieve

I want to make an object in react which will calculate one its key value from other keys using this function and the 'this' keyword so that I can use this function dynamically with many input fields object.

func = function (c) {
    return this.a + this.b + c;
};

obj1 = {
    a: 1,
    b: 2,
    value: func(5),
};

obj2 = [
    { a: 2, b: 3, value: func(6) },
    {
        a: 4,
        b: 5,
        value: func(7),
    },
];

// expected result
console.log(obj1.value); // 8
console.log(obj2[0].value); // 16
DecPK
  • 24,537
  • 6
  • 26
  • 42
xxxhomie21
  • 71
  • 8
  • 1
    Relevant: [How does the "this" keyword work, and when should it be used?](https://stackoverflow.com/q/3127429) – VLAZ Aug 05 '22 at 11:15

2 Answers2

0

I guess the simplest solution would to flip this around: Pass the object to the function, let it add the property and return the very same object:

const func = function (obj, c) {
  obj.value = obj.a + obj.b + c;
  return obj;
};

const obj1 = func({
    a: 1,
    b: 2,
}, 5);

const obj2 = [
    func({ a: 2, b: 3 }, 6),
    func({
        a: 4,
        b: 5,
    }, 7),
];

// expected result
console.log(obj1.value); // 8
console.log(obj2[0].value); // 16

(no idea how the second example would result in 16 though)

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
-1

At the moment func is called, this is set to window object, because the object you want to use it in, doesn't exist yet.

You can try returning a function from func

const func = function(c) {
  return function() {
    return this.a + this.b + c
  }
}

const obj1 = {
  a: 1,
  b: 2,
  value: func(5),
}

const obj2 = [{
    a: 2,
    b: 3,
    value: func(6)
  },
  {
    a: 4,
    b: 5,
    value: func(7)
  }
]

// expected result
console.log(obj1.value()) // 8
console.log(obj2[0].value()) // 11
Konrad
  • 21,590
  • 4
  • 28
  • 64