我知道对于 javascript 的编写方式有很多不同的看法,但我想知道我的编写方式是否合适。我不想进入工作岗位编写没人理解的代码。
这段代码的基本前提是测试对象的自定义事件处理程序,想知道是否有任何明显的“你不应该这样做”类型的东西
function EventClass() {
var self = this;
var events = {};
var i = 0;
self.fire = function(evt, args) {
for (x in events[evt])
events[evt][x].call(this, args);
}
self.on = function(evt, fn) {
if (events[evt] == null) {
events[evt] = []
}
events[evt].push(fn);
}
};
function Human(x, y) {
var self = this;
self.__proto__ = new EventClass();
var xCoord = 0;
var yCoord = 0;
self.events = {
"MOVEMENT" : "movement"
};
self.init = function(x,y) {
xCoord = x;
yCoord = y;
}
self.draw = function(context) {
context.beginPath();
context.arc(xCoord,yCoord,10,0,Math.PI*2,true);
context.closePath();
context.fill();
}
self.moveLeft = function() {
xCoord -= 5;
self.fire(self.events.MOVEMENT, xCoord);
}
self.init(x,y);
};
function Player(x, y) {
var self = this;
self.__proto__ = new Human();
self.init(x,y);
};
function Canvas(c) {
var self = this;
var canvas;
var context;
var objects = [];
self.init = function(c) {
canvas = c;
context = canvas.getContext("2d");
};
this.redraw = function() {
context.clearRect(0,0,300,300);
for (x in objects) {
objects[x].draw(context);
}
}
this.addObject = function(obj) {
objects.push(obj);
obj.on(obj.events.MOVEMENT, function(coord) {
console.log(coord);
self.redraw();
});
};
self.init(c);
}
var canvas = new Canvas(document.getElementById("canvas"));
var human0 = new Human(75,75);
canvas.addObject(human0);
var human1 = new Human(100,100);
canvas.addObject(human1);
var player = new Player(200,200);
canvas.addObject(player);
canvas.redraw();