我在这个用于 HTML 5 Canvas 的粒子系统的早期阶段遇到了紧迫的问题。当我尝试检索我的 Particle
类对象的属性时,它返回 undefined
而我不明白为什么!
class Particle {
contructor(context, width, height) {
this.x = width / 2;
this.y = height / 2;
this.radius = Math.random() * 5 + 5;
}
};
var App = {
canvas: document.getElementById('canvas'),
ctx: canvas.getContext('2d'),
initialize: function() {
this.canvas.width = window.innerWidth;
this.canvas.height = window.innerHeight;
},
draw: function() {
var P = new Particle(this.ctx, this.canvas.width, this.canvas.height);
alert(P.x); // Why does this return undefined?
this.ctx.beginPath();
this.ctx.arc(P.x,P.y,P.radius,0,2*Math.PI);
this.ctx.stroke()
}
};
App.initialize();
App.draw();
最佳答案
我认为您的 Particle
类构造函数中有一个愚蠢的拼写错误:它应该读作 constructor
。例如:
class Particle {
constructor(context, width, height) {
...
}
};
因为您没有实际上初始化您的P
变量,所以所有属性都是未定义
的。
关于javascript - 对象属性在 Javascript 上返回 'undefined',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43881127/