[英]Adding a prototype to an object constructor defined in an object literal
Hey so I have an object constructor method inside and object literal, and I defined a prototype for the constructor like this 嘿,所以我有一个对象构造函数方法和一个对象常量,我为构造函数定义了一个原型
objectLiteralKey:(function()
{
var f=function()
{
...
};
f.prototype=ObjectInstance;
return f;
}()),
//inside an object literal
is there any reason this pattern of defining the prototype should be avoided? 有什么理由应该避免这种定义原型的模式? or perhaps another way thats better somehow?
或者也许是另一种更好的方式?
EDIT: by the way the object literal is within a self invoking function which holds the laserPrototype, I put it there because there is another "enemy" that requires the same prototype 编辑:顺便说一下,对象字面量在一个拥有laserPrototype的自调用函数中,我把它放在那里,因为还有另一个“敌人”需要相同的原型
full code http://jsfiddle.net/m2DwT/ 完整代码http://jsfiddle.net/m2DwT/
is there any reason this pattern of defining the prototype should be avoided?
有什么理由应该避免这种定义原型的模式?
No. Apart from readability, maybe. 不。除了可读性,也许。
or perhaps another way thats better somehow?
或者也许是另一种更好的方式?
I think there are too many unecessary immedieately invoked function expressions in your code, which you could omit. 我认为您的代码中有太多不必要的立即调用的函数表达式,您可以省略。 It might be better to put the constructors right before their 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: …
}
}())
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.