简体   繁体   中英

Changing value of class variable

I started OOP few days ago so i'm not experianced. 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. And now i want to change all of their speed values to 2 without using for loop.

You can use prototype for that. 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!
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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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