简体   繁体   English

我如何将一个变量分配给另一个变量加上一个常量

[英]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. 我正在寻找的是类似于C#的get属性的内容,但适用于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. 假设我传入了5和3。然后a = 5,b = 3和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. 所以现在a = 10,b = 3和c = 10。 This is not what I want, I want c=15 to reflect the change in a. 这不是我想要的,我希望c = 15反映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. 我已经进行了大约40分钟的研究,但感到非常沮丧,以至于我似乎无法按照我想要的方式来进行这项工作。 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) 我尝试了函数,尝试了示例中的内容,并尝试使用ES5中的获取/设置功能(当他们加入聚会时为6?idk)

Anyway, help appreciated, something simple and frustrating. 无论如何,帮助表示赞赏,简单而令人沮丧。 I hate working in JS, lord deliver me from this evil ;) 我讨厌在JS中工作,上帝让我摆脱了这种邪恶;)

What I am looking for is something similar to a get property of C#, but for JS. 我正在寻找的是类似于C#的get属性的内容,但适用于JS。

That would be a get property: 那将是一个get属性:

 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); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM