javascript - 将原型(prototype)添加到对象字面量中定义的对象构造函数

标签 javascript

嘿,所以我在里面有一个对象构造函数方法和对象字面量,我像这样为构造函数定义了一个原型(prototype)

objectLiteralKey:(function()
{
    var f=function()
    {
        ...
    };

    f.prototype=ObjectInstance;

    return f;
}()),
//inside an object literal

有什么理由应该避免这种定义原型(prototype)的模式吗?还是另一种更好的方式?

编辑:顺便说一句,对象字面量在一个包含激光原型(prototype)的自调用函数中,我把它放在那里是因为还有另一个“敌人”需要相同的原型(prototype)

完整代码 http://jsfiddle.net/m2DwT/

最佳答案

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/

相关文章:

javascript - 状态更新后 react 不重新渲染DOM

javascript - innerHTML 可以跨不同行工作吗?

javascript - 如果折叠其中一个 Accordion 元素,如何隐藏 block ?

javascript - 如何在点击时将 div 内容置于底部边框

javascript - 输入字段,强制格式 00 :00. 00

javascript - 使用 `Map` 如何编写将华氏度值数组转换为摄氏度的函数?

javascript - VSCode 是否支持 react 中的 CSS 变量?错误

javascript - 为什么node.js比apache 2.4慢这么多

javascript - 删除点。从字符串末尾开始签名

javascript - 如何在 Angular.js 中组合两个 Controller ?