繁体   English   中英

如何使用“ new”将对象变量添加到数组?

[英]How to add object variable to an array using “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;
        }

    };

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

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

但这会引发错误:

“未捕获的TypeError:背景不是构造函数”

尽管它可以正常使用: function name() {} var test_var = new name()所以我的猜测是,“ new”仅适用于函数。 但是,如何使用像以前那样的可变对象呢? (我想在一个数组中有多个它们,而不仅仅是对一个对象的多个引用)

使用ES5及以下版本,您可以创建一个充当构造函数的函数。 this内部使用this属性将属性绑定到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); 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM