简体   繁体   中英

Add object to array from constructor

I'm currently working on a platform game which will have a lot of different blocks that will serve as walls and platforms. In order to know if a player has arrived att a point where there's an obstacle, I'd like to loop through an array of all blocks.

I could of course just add the objects to the array after I've created them:

    var blockArray = [];
    var block1 = new Block();
    blockArray.push(block1);

But lets face it, I'm lazy and the code becomes a bit cluttered. Is there some way to add the object to the array from inside the constructor, something like this:

    var blockArray = [];        
    function Block () {
          blockArray.push(this.Block);
    }

where this.Block means the newly created object.

Is there any way to reference an object like this?

Thanks in advance

Is there any way to reference an object like this?

Yes, it's literally this .

 var blockArray = []; function Block() { this.foo = 42; blockArray.push(this); } new Block(); console.log(blockArray); 

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