简体   繁体   中英

Javascript: assigning new objects with unique random properties

I'm attempting to create an array of objects based on a constructor. During creation of the constructed objects each is assigned an ID & a random integer as the first value of an array.

var defaults = {
  x: 0, 
  y: 0, 
  d: [1,1], // destination 


  s: 2 // speed 
};

var stage = document.getElementById('stage');

var oM = function ( vars ) {

    var vars = vars;

    this.fn = {};
    this.v = vars.v;

    this.i = vars.i;
    this.v.d = [ 0, 0 ];

    this.init = function( i ) {

        var r = Math.floor( Math.random() * 999);
        var d = Math.floor( Math.random() * 999);

        var e = document.createElement('div');
        e.id = 'bit-' + i;
        e.classList.add('bit', 'mob', 'test');

        stage.appendChild(e);

        this.v.x = r;
        this.v.d[0] = d;

        console.log( this.v.d );

        this.e = document.getElementById( 'bit-' + i );
        this.e.style.left = this.v.x ;

    };

    this.move = function() {

        var i = this.i;
        var p = this.v.x;  
        var d = this.v.d[0]; 
        var s = this.v.s; 
        var m = 'stay';

        if ( ( p > d && ( p - s ) <= d ) || ( p < d && ( p + s ) >= d ) ) {
            p = d;
        } else if ( p > d ) {
            // move W 
            p = p - s;
            m = 'west';
        } else if ( p < d ) {
            // move E
            p = p + s;
            m = 'east';
        } 

        // console.log('index: ' + i + ' x: ' + p + ': moved: ' + m + ' @' + s + ': toward: ' + d + ' from: ' + this.v.x);
        this.v.x = p;
        this.e.style.left = this.v.x ;
        console.log( this.v.d );

    }
};



var eng = {};

eng.arr = [];

eng.init = function() {

    for ( var i = 0; i < 20; i++ ) {

        var u = new oM( { 
            i: i,
            v: defaults
        });


        u.init( i );
        eng.arr.push( u );
        // console.log( t );

    };

}

eng.turn = function() { 

    for ( var i = 0; i < eng.arr.length; i++ ) {

        console.log( eng.arr[ i ].v.d );
      // eng.arr[ i ].move();

    };

};


var f = 0;

eng.init();




console.time('turn: 0');

window.run = function () {

    if (f <= 9.1300) {
        window.requestAnimationFrame( run );

        eng.turn();
        console.timeEnd('turn: ' + f);
        f = f + 1;
        console.time('turn: ' + f);

    };

};

run();

In the above you can see two separate namespaces: oM contains methods for object construction & manipulation. eng contains methods & context for interacting with all objects.

When the objects are first constructed they each have a unique random number here: this.vd[0] or eng.arr[#].vd[0] (currently output to console).

However once the for in eng.init() has finished you'll note that all the objects in the array eng.arr now have the same (the last added object's) value for this.vd[0] .

How is the final objects value being set to the other array items? The ID key is not being affected.

How is the final objects value being set to the other array items? The ID key is not being affected.

Because v (and, consecutively, vd ) is the same hash/object for all your created objects. You're mutating the same place in memory. Copy/clone the defaults for each object.

The ID isn't repeated because you reassign the reference to a new object rather than mutate existing object.

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