代码:
particles.push(new function() {
this.x = 500
this.y = 500
this.vx = 2
this.vy = 2
this.radius = 5
this.expireTimer = setTimeout(function(self) {
return function() {
particles.splice(particles.indexOf(self), 1)
}
}(this), Math.floor(Math.random() * 500) + 500)
})
我的问题是:在这种情况下,还有其他方法可以获取实际的this
属性吗?在这种情况下,有没有办法在不使用new function()
并像往常一样用对象推动数组的情况下获得this
,例如particles.push({x: 23})
而不是particles.push(new function() {this.x = 23})
?
不能从对象文本内部引用对象本身,除非您有一个将对象分配到的变量:
var obj = {
timer: setTimeout(function () {
doSomething(obj);
}, 1000)
};
在您的情况下,如果您的主要目标是更简单的语法,我建议您编写一个辅助函数,负责粒子创建/销毁:
function createParticle(particle) {
particles.push(particle);
particle.expireTimer = setTimeout(function () {
particles.splice(particles.indexOf(particle), 1);
},Math.floor(Math.random() * 500) + 500);
}
使用此函数,您可以通过简单地调用以下命令来创建新粒子:
createParticle({
x: 500,
y: 500,
vx: 2,
vy: 2,
radius: 5
});