看到你无法访问javascript对象中兄弟方法的属性,我一直在使用prototype方法来扩展这些属性。
var ColorGen = function ColorGen() {}
ColorGen.prototype = {};
ColorGen.prototype.settings = {
gridContainer : 'gridContainer',
xSquareCount : 50,
ySquareCount : 50,
xLength : 500,
yLength : 500,
gridArr : []
};
ColorGen.prototype.totalSquares = function() {
return (this.settings.xSquareCount * this.settings.ySquareCount);
};
ColorGen.prototype.squareDim = function(length, count) {
return Math.round(length / count);
};
ColorGen.prototype.hueStep = function() {
return (360/this.totalSquares());
};
ColorGen.prototype.populateGrid = function() {
var width = this.squareDim(this.settings.xLength, this.settings.xSquareCount),
height = this.squareDim(this.settings.yLength, this.settings.ySquareCount);
for(var i=0, k = this.settings.xSquareCount * this.settings.ySquareCount; i < k; i++ ) {
var square = document.createElement('DIV');
square.setAttribute("style", "background: hsla("+(Math.round(this.hueStep() * i))+", 100%, 50%, 1.0); width: "+width+"px; height: "+height+"px; display: inline-block; position: relative;");
this.settings.gridArr.push(square);
}
};
ColorGen.prototype.setGridContainer = function() {
document.getElementById(this.settings.gridContainer).setAttribute('style', 'width: '+this.settings.xLength+'px; height: '+this.settings.yLength+'px; position: relative; overflow: hidden;');
}
ColorGen.prototype.appendGrid = function() {
var gridSquares = this.settings.gridArr;
for(square in gridSquares) {
if (document.getElementById(this.settings.gridContainer) !== null) {
document.getElementById(this.settings.gridContainer).appendChild(gridSquares[square]);
}
}
}
var colorgen = new ColorGen();
colorgen.setGridContainer();
colorgen.populateGrid();
colorgen.appendGrid();
这是小提琴: http://jsfiddle.net/Ua6Mp/embedded/result/
问题:这是原型方法的合理利用吗?如果没有,扩展对兄弟方法属性的访问的惯例是什么?
我可能没有正确地说这个。如果您认为可以更清楚地描述,请随时编辑此问题
答案 0 :(得分:0)
当您使用name.prototype.method = function() {}
时,name是一个对象,您正在处理JavaScript类。据我所知,许多JavaScript框架都使用它(也许是jQuery)。我还没有听说过JavaScript类中的属性。