2

I've got this object variable:

var Background = {
        x: 0,
        y: 0,
        speed: 4,

        initialize: function (x, y){
            this.x = x;
            this.y = y;

        move: function(){
            this.x -= this.speed;
        }

    };

And I'd like to create new object variable and add it to an array:

background_container = []
background_container.push(new Background())

But it throws an error:

"Uncaught TypeError: Background is not a constructor"

Although it works with normal: function name() {} var test_var = new name() So my guess is that "new" works only for functions. But how can I do it with variable objects like the one before? (I want to have multiple of them in one array and not just multiple references to one object)

1 Answer 1

6

With ES5 and below you can create a function which acts as a constructor. Use this inside to bind properties to the current object which is returned from the new operator. Also you can leave the initalize function (if you intend to use this only one time) and pass parameters into the function or constructor directly.

function Background(x, y) {

   this.x = x || 0;
   this.y = y || 0;
   this.speed = 4;

   this.move = function() {
       this.x -= this.speed;
   }

};

var backgrounds = [];
backgrounds.push(new Background(1, 3));

console.log(backgrounds[0].x);
console.log(backgrounds[0].y);

With ES6 and higher you can use Ecmascript's new syntax for creating classes.

class Background {

   constructor(x = 0, y = 0) {
      this.x = x;
      this.y = y;
      this.speed = 4;
   }

   move() {
       this.x -= this.speed;
   }

};

const backgrounds = [];
backgrounds.push(new Background(1,3));

console.log(backgrounds[0].x);
console.log(backgrounds[0].y);

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.