2017-10-21 16 views
2

J'ai cette variable d'objet:Comment ajouter une variable d'objet à un tableau en utilisant "new"?

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

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

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

    }; 

et je voudrais créer une nouvelle variable d'objet et l'ajouter à un tableau:

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

Mais il renvoie une erreur:

"Uncaught TypeError: Background is not a constructor"

Bien que cela fonctionne avec la normale: function name() {} var test_var = new name() Donc, je suppose que "nouveau" ne fonctionne que pour les fonctions. Mais comment puis-je le faire avec des objets variables comme celui d'avant? (Je veux avoir plusieurs d'entre eux dans un tableau et pas seulement plusieurs références à un objet)

Répondre

6

Avec ES5 et ci-dessous vous pouvez créer une fonction qui agit comme un constructeur. Utilisez this à l'intérieur pour lier les propriétés à l'objet actuel renvoyé par l'opérateur new. Aussi, vous pouvez laisser la fonction initalize (si vous avez l'intention de l'utiliser une seule fois) et transmettre directement les paramètres dans la fonction ou constructor.

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

Avec ES6 et plus vous pouvez utiliser la nouvelle syntaxe de ECMAScript pour la création de 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);