我是javascript的新手,正在尝试创建一个对象,然后可以使用的实例填充列表.我拥有的这段代码有效,但是拥有“ this”感觉很多余.每行关键字.有没有更整洁/更合适的方式来创建这样的对象?
这是我当前的对象:
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中是强制性的,即使其他语言也可以推导出来.
今天是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);