简体   繁体   English

更改类变量的值

[英]Changing value of class variable

I started OOP few days ago so i'm not experianced. 我几天前开始OOP,所以我没有经验。 I'm wondering is it any chance to change value of class property in order to affect on all objects, which use that class? 我想知道是否有机会更改类属性的值以影响所有使用该类的对象?

Example: 例:

function Balloon(ID){
    this.ID = ID;
    this.speed = 1; 
}

Let's say I have 5 Balloon objects. 假设我有5个Balloon对象。 And now i want to change all of their speed values to 2 without using for loop. 现在我想不使用for循环将所有速度值更改为2。

You can use prototype for that. 您可以使用prototype Checkout the example below: 查看以下示例:

function Balloon(ID){
    this.ID = ID;
}

Balloon.prototype.speed = 1;

b1 = new Balloon(1);
b2 = new Balloon(10);

console.log(b1.speed); // outputs 1
Balloon.prototype.speed = 15;
console.log(b2.speed); // outputs 15, which is now also 15 for all other Balloon instances

Well you would need to edit the object's local static variables: 那么,您将需要编辑对象的局部静态变量:

var Balloon = (function(){

    var speed = null;

    function Balloon(ID){
        this.ID = ID;
        speed = 1; 
    }

    return Balloon;

})();

The problem is that now all balloons would share the same speed! 问题在于,现在所有气球都会共享相同的速度! AHH! AHH!
That's not good at all... and in order to change the speed you would need to create a getter/setter for it... Which you really do not need in your case. 这一点都不好……为了改变速度,您需要为此创建一个吸气剂/吸气剂……您的情况中确实不需要。

So -- to change all possible Balloon type object's speed at the same time, while allowing for each Balloon to technically have different speeds, the only conclusion is to go to each Balloon object and change the speed (sorry) 所以-要同时更改所有可能的Balloon类型对象的速度,同时允许每个Balloon在技术上具有不同的速度,唯一的结论是转到每个Balloon对象并更改速度(对不起)

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

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