Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change a value in an object in a function

Tags:

javascript

So in my code I have an object:

function myObject(value1, value2, value3){
    this.value1 = value1;
    this.value2 = value2;
    this.value3 = value3;
}

Then I have a function:

function myFunction(value1, value2, value3) {
    value1 += value2;
    value3 += 1;
};

How could I use something like this to change the value of the object. For example:

var object1 = new myObject(1,2,3);

So eventually, value1 would become 3, and value3 would become 4. Thank you in advance, I'm new to OOP

like image 488
person341 Avatar asked Aug 10 '26 15:08

person341


2 Answers

You can pass arguments to that function by spreading them. And return an object from that function and then merge it with this

function myObject(...values){
    Object.assign(this,myFunction(...values))
}
function myFunction(value1, value2, value3) {
    value1 += value2;
    value3 += 1;
    return {value1,value2,value3};
};

const x = new myObject(1,2,3);
console.log(x);
like image 70
Maheer Ali Avatar answered Aug 13 '26 06:08

Maheer Ali


You can pass a reference of your object to myFunction and there you can change the values.

function myObject(value1, value2, value3) {
  this.value1 = value1;
  this.value2 = value2;
  this.value3 = value3;
}

function myFunction(obj) {
  obj.value1 += obj.value2;
  obj.value3 += 1;
};

var object1 = new myObject(1, 2, 3);
myFunction(object1);
console.log(object1)
like image 31
Vladu Ionut Avatar answered Aug 13 '26 06:08

Vladu Ionut



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!