2014-02-09 88 views
1
定義的對象構造

嘿所以我有內部的對象構造方法和對象文字,我所定義的原型這樣添加原型中的對象字面

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

    f.prototype=ObjectInstance; 

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

構造沒有任何理由這樣應該避免定義原型的模式?或者可能是另一種更好的方式?

編輯:按字面的對象是持有laserPrototype自調用函數中的方式,我把它放在那裏,因爲還有另外一個「敵人」,要求相同的原型

全碼http://jsfiddle.net/m2DwT/

+1

什麼是'eLasers'? 「敵人」是其中一員的對象字面量是什麼,它是單身人士嗎? |看到你的編輯,如果你可以只是把那個自我調用函數放在那裏(並且通過用橢圓替換它們來省略不必要的部分將是很好的...) – Bergi

+0

kk,我剪掉了不重要的部分 –

回答

2

是否有任何理由應該避免這種定義原型的原因?

不可以。除了可讀性,也許。

或者可能是另一種更好的方式嗎?

我認爲你的代碼中有太多不必要的直接調用的函數表達式,你可以忽略它。將構造函數置於原型之前可能會更好:

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: … 
    } 
}())