【问题标题】:javascript better way to create object with a method using functionjavascript 使用函数创建对象的更好方法
【发布时间】:2019-03-20 14:59:13
【问题描述】:

我是 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;
    }
}

提前感谢您的帮助

【问题讨论】:

    标签: javascript function object methods


    【解决方案1】:

    不幸的是,this 在 Javascript 中是强制性的,即使其他语言推断它也是如此。

    今天Ecmascript classes are supported by any browser excepting IE。如果您想使用面向对象编程,这可能是使用类语法的好方法。

    class Particle {
        constructor(x, y) {
          this.x = x;
          this.y = y;
          this.xspeed = 0;
          this.yspeed = 0;
          this.xacc = 0;
          this.yacc = 0;
        }
    
        update() {
            this.x += this.xspeed;
            this.y += this.yspeed;
            this.xspeed += this.xacc;
            this.yspeed += this.yacc;
        }
    }
    
    const particle = new Particle(1, 2);
    particle.update();
    console.log(particle);

    【讨论】:

    • 虽然我有点难过this. 是强制性的,但我没有意识到可以像这样使用类,它几乎正是我试图模仿的。所以感谢本杰明的回复!
    【解决方案2】:

    你可以使用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;
      },
    });
    

    【讨论】:

    • 这看起来确实更简洁,但 Tino 的另一条评论说我当前的方法是有意义的,因为我想使用多个具有自己值的实例。这是否意味着对于这些方法中的每一个,变量分配给对象的方式存在差异?谢谢
    • @adam 没有,不知道他在说什么。
    • 好的,谢谢,有没有办法在不使用 function() 声明的情况下使用构造函数创建这种对象?因为使用 object = {} 的标准赋值看起来更干净,但它似乎不支持构造函数。
    • 太好了,我更喜欢函数方法,非常感谢乔纳斯的帮助。
    【解决方案3】:

    关于this 的高使用率,您可以使用Object.assign 来修复基代码中值赋值的高使用率。 (this.value = value)

    由于您希望多个实例具有自己的值,因此将this 范围用于您要使用的值是合乎逻辑的。 (使用this 范围内定义的值)

    【讨论】:

    • 感谢您的回复,我在 Jonas 的回答中留下了评论,询问我的方法和 object.assign 方法之间的区别,有吗?
    • Object.assign 函数会将值绑定到 this 范围,结果没有区别,Object.assign 更干净,您应该这样做。我的意思是说您在这种情况下使用this 范围并不是一件坏事。 @Jonas 的回答很棒。再看一遍我的答案,也不是很清楚,我会编辑它
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-19
    • 1970-01-01
    • 2012-04-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多