javascript - 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;
}
}
提前感谢您的帮助
解决方案
您可以使用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;
},
});
推荐阅读
- google-play-console - 尝试将图标上传到 Google Play 控制台时出错
- rust - split(' ') 和 split_whitespace() 之间的区别
- java - 无法在安卓上阅读短信
- firebase - 如何从 firestore firebase 上的查询快照中获取长度?
- java - 无法获取用户的位置和地址
- postgresql - PgAdmin4 - “NoneType”对象没有属性“值”
- regex - Tcl - 如何通过正则表达式在最后一个字符之后添加文本?
- ssl - 在 Nest.js 中的 3 个不同端口上使用安全 Websocket
- django - Django 无法在 FloatField 中保存空白值
- java - 自定义排序具有 2 列的 2 个 csv 文件并在 Java 中打印差异