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()
沒有啓動它作爲一個新的對象時,它未能通過不具功能的塗料。
不錯。作品:)皮特說,把它包裝成括號,如:'this.grid =(function(p){...})(this);'。這可能會帶來什麼困難嗎?另外:可以說'this.paint = function(){...} return {paint:this.paint}'而不是? (要減少代碼中的縮進級別) – user13500
@ user13500不需要額外的括號,否則不能在函數內部使用this.paint。 –
我可能錯過了溝通。我的意思是這樣的:http://pastebin.com/raw.php?i=F92SrRLW - 它適用於我的快速測試,但可能還有其他一些複雜性。 – user13500