2014-02-06 77 views
3

具有各種功能的原型對象,主要是用於畫布。通常是這樣的:讓原型功能具有繼承環境的子功能

function CanvasPain() { 
    ... 
} 

CanvasPaint.prototype.drawFoo = function(x, y) { 
    this.ctx.moveTo(x, y); 
    ... 
}; 

我有一個像paintGrid一些功能(),我想有子功能 - 而且是基於財產的對象。 (不知道如何詞這一點。)例:

CanvasPaint.prototype.grid = function() { 
    this.paint = function() { 
     this.ctx.moveTo(0, 0); 
     // Here this.rows should be a property of CanvasPaint.prototype.grid() 
     // and not CanvasPaint() 
     for (var i = 0; i < this.rows; ++i) { 
      ... paint lines 
     } 
    }; 
}; 

然後能夠做到,例如說:

var CP = new CP(); 

// And in some function: 
    this.grid.rows = 10; 
    this.grid.cols = 10; 
    this.grid.paint(); 

之所以這樣做是爲了讓代碼更乾淨。截至目前我使用這樣的事情:

function CanvasPain(arg) { 
    ... 
    this.properties = {}; 
    this.properties.fig1 = {a:123, b:111}; 
    this.properties.grid = { 
       rows = arg.rows; 
       cols = arg.cols; 
       live = 1; 
    }; 
} 

CanvasPaint.prototype.paintGrid = function() { 
    this.ctx.clearRect(0, 0, this.width, this.height); 
    this.ctx.moveTo(0, 0); 
    for (var i = 0; i < this.properties.grid.rows; ++i) 
     ... 
} 

CanvasPaint.prototype.foo = function() { 
    this.paintGrid(); 
} 

這看起來不太好我。我想擺脫「屬性」對象,而是將這些屬性設置爲相關函數(如果有)。像網格的行和列屬於功能對象網格

我的問題是我如何在代碼中構造這樣的網格函數可以繼承母對象的屬性?

如果我說CP.grid = new CP.grid();它成爲一個獨立的對象,從而失去了this.cxt等,如果我做CP.grid.paint()沒有啓動它作爲一個新的對象時,它未能通過不具功能的塗料。

回答

2

您的paint()功能需要訪問CanvasPain對象以及它自己的屬性,例如rowscols

所以,每個新CanvasPain對象,你需要創建一個專用.grid屬性:

function CanvasPain(arg) 
{ 
    // ... 

    // generate grid object 
    this.grid = function(p) { 
     // return public interface 
     return { 
      paint: function() { 
       p.ctx.moveTo(0, 0); 
       for (var i = 0; i < this.rows; ++i) { 
        //... paint lines 
       } 
      } 
     }; 
    }(this); 
} 

p變量的函數指向CanvasPain實例內。

var CP = new CanvasPain(); 

CP.grid.rows = 10; 
CP.grid.cols = 10; 
CP.grid.paint(); 
+0

不錯。作品:)皮特說,把它包裝成括號,如:'this.grid =(function(p){...})(this);'。這可能會帶來什麼困難嗎?另外:可以說'this.paint = function(){...} return {paint:this.paint}'而不是? (要減少代碼中的縮進級別) – user13500

+0

@ user13500不需要額外的括號,否則不能在函數內部使用this.paint。 –

+0

我可能錯過了溝通。我的意思是這樣的:http://pastebin.com/raw.php?i=F92SrRLW - 它適用於我的快速測試,但可能還有其他一些複雜性。 – user13500