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
CodePudding user response:
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)
CodePudding user response:
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