嘿,所以我在里面有一个对象构造函数方法和对象字面量,我像这样为构造函数定义了一个原型(prototype)
objectLiteralKey:(function()
{
var f=function()
{
...
};
f.prototype=ObjectInstance;
return f;
}()),
//inside an object literal
有什么理由应该避免这种定义原型(prototype)的模式吗?还是另一种更好的方式?
编辑:顺便说一句,对象字面量在一个包含激光原型(prototype)的自调用函数中,我把它放在那里是因为还有另一个“敌人”需要相同的原型(prototype)
最佳答案
is there any reason this pattern of defining the prototype should be avoided?
没有。除了可读性,也许。
or perhaps another way thats better somehow?
我认为你的代码中有太多不必要的立即调用的函数表达式,你可以省略。将构造函数放在原型(prototype)之前可能会更好:
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: …
}
}())
关于javascript - 将原型(prototype)添加到对象字面量中定义的对象构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21665669/