Hoopla70
Hoopla70

Reputation: 111

How would I assign a variable to another variable plus a constant

What I am looking for is something similar to a get property of C#, but for JS. An example of what I am wanting would look like this:

function myObj(a, b){
     this.a = a;
     this.b = b;
     this.c = a + 5;
}

Let's say I passed in a 5 and a 3. Then a=5, b=3, and c=10. Which is what I want. Now I want to come down into somewhere else and say

obj.a = 10;

So now a=10, b=3, and c=10. This is not what I want, I want c=15 to reflect the change in a. I have been working on this for about 40 minutes and am so frustrated that I cannot seem to get this to work the way I would like. I've tried functions, I've tried what is in the example, and I have tried using the get/set features in ES5 (6? idk when they joined the party)

Anyway, help appreciated, something simple and frustrating. I hate working in JS, lord deliver me from this evil ;)

Upvotes: 0

Views: 43

Answers (1)

Ry-
Ry-

Reputation: 224886

What I am looking for is something similar to a get property of C#, but for JS.

That would be a get property:

class MyObj {
    constructor(a, b) {
        this.a = a;
        this.b = b;
    }

    get c() {
        return this.a + 5;
    }
}


let obj = new MyObj(5, 3);
console.log(obj.c);
obj.a = 10;
console.log(obj.c);

Upvotes: 4

Related Questions