考虑到您不能访问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/
问:这是对原型方法的适当利用吗?如果不是,扩展对同级方法属性的访问的约定是什么?
我可能说得不对。如果您认为可以更清楚地描述这个问题,请随时编辑它。
发布于 2013-07-21 08:41:25
当您使用name.prototype.method = function() {}时,名称是一个对象,您处理的是JavaScript类。据我所知,许多JavaScript框架都使用这个(可能也是jQuery )。我还没有听说过JavaScript类中的属性。
https://stackoverflow.com/questions/17769997
复制相似问题