0

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

2
  • The constructor really should not do that. Write a function addNewBlock() { blockArray.push(new Block); } that puts the new instance on that global array. Commented May 28, 2018 at 21:24
  • Be careful with the "this" keyword, in this case, the "this" is implicit which is the most common. Commented May 28, 2018 at 22:18

1 Answer 1

5

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.