首页 > 解决方案 > javascript 使用函数创建对象的更好方法

问题描述

我是 javascript 新手,正在尝试创建一个对象,然后我可以用其实例填充列表。这段代码我有工作,但有“这个”感觉是多余的。每一行的关键字。有没有更整洁/更合适的方法来创建这样的对象?

这是我当前的对象:

    var Particle = function(x, y) {
    this.x = x;
    this.y = y;
    this.xspeed = 0;
    this.yspeed = 0;
    this.xacc = 0;
    this.yacc = 0;

    this.update = function() {
        this.x += this.xspeed;
        this.y += this.yspeed;
        this.xspeed += this.xacc;
        this.yspeed += this.yacc;
    }
}

提前感谢您的帮助

标签: javascriptfunctionobjectmethods

解决方案


您可以使用Object.assign和对象文字:

var Particle = function(x, y) {
 Object.assign(this, {
   x, y,
   xspeed: 0,
   yspeed: 0,
   xacc: 0,
   yacc:0,
 });
 //...
};

由于您没有使用继承,您也可以只返回一个新对象:

const Particle = (x, y) => ({
   x, y,
   xspeed: 0,
   yspeed: 0,
   xacc: 0,
   yacc:0,
   update() {
    this.x += this.xspeed;
    this.y += this.yspeed;
    this.xspeed += this.xacc;
    this.yspeed += this.yacc;
  },
});

推荐阅读