嗨,所以我有一个对象构造函数方法和一个对象常量,我为构造函数定义了一个原型
objectLiteralKey:(function()
{
var f=function()
{
...
};
f.prototype=ObjectInstance;
return f;
}()),
//inside an object literal
有什么理由应该避免这种定义原型的模式?或者也许是另一种更好的方式?
编辑:顺便说一下,对象字面量在一个拥有laserPrototype的自调用函数中,我把它放在那里,因为还有另一个“敌人”需要相同的原型
有什么理由应该避免这种定义原型的模式?
不。除了可读性,也许。
或者也许是另一种更好的方式?
我认为您的代码中有太多不必要的立即调用的函数表达式,您可以省略。最好将构造函数放在原型之前:
var laser = (function () {
var eLasers = []; // local variable declarations
var pLasers = []; // for encapsulation
function Player() {
this.x = window.player.x; // wait, what? Maybe parameters
this.y = window.player.y; // would fit better.
pLasers.push(this);
this.destroy = function () {
pLasers.splice(pLasers.indexOf(this), 1);
}
}
function Enemy() {
…
}
// here, Player.prototyp !== Enemy.prototype
// but I don't think that is really necessary
Player.prototype.draw = Enemy.prototype.draw = function() {
ctx.beginPath();
ctx.arc(this.x, this.y, 5, 0, 2 * Math.PI);
ctx.stroke();
};
return {
enemy: Enemy,
player: Player,
step: …
}
}())
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句