javascript - 如何使用 "new"将对象变量添加到数组?

标签 javascript arrays

我有这个对象变量:

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

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

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

    };

我想创建新的对象变量并将其添加到数组中:

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

但是它抛出一个错误:

"Uncaught TypeError: Background is not a constructor"

虽然它适用于正常情况: 函数名() {} var test_var = 新名称() 所以我的猜测是"new"仅适用于功能。但是我怎样才能像以前那样使用可变对象呢? (我想在一个数组中包含多个,而不仅仅是对一个对象的多个引用)

最佳答案

在 ES5 及以下版本中,您可以创建一个充当构造函数的函数。在内部使用 this 将属性绑定(bind)到从 new 运算符返回的当前对象。您也可以保留 initalize 函数(如果您打算只使用一次)并将参数直接传递给函数或 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);

在 ES6 及更高版本中,您可以使用 Ecmascript 的新语法来创建类。

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

关于javascript - 如何使用 "new"将对象变量添加到数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46860869/

相关文章:

arrays - 无法索引到数组以将其转换为哈希表

arrays - 如何将类型删除的列表转换为 Kotlin 中的数组?

php - 具有 NULL 键的数组

javascript - 为什么WebDriverJS是异步的?

javascript - 自动展开响应式数据表的子行

javascript - 检查 div 是否包含任何溢出的内联 block 跨度

c - 大批。访问 0xFFFFFFFF 元素

javascript - 在浏览器的本地存储中保留旧数据

javascript - 是 "if (somestring in {' oneoption' :false, 'secondoption' :false})"considered bad practise in javascript?

PHP:数组 $_POST 循环问题