1

看到您无法访问 javascript 对象中同级方法的属性,我一直在使用原型方法来扩展这些属性。

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/

问题:这是对原型方法的适当利用吗?如果不是,那么扩展对兄弟方法属性的访问的约定是什么?

我的措辞可能不正确。如果您认为可以更清楚地描述此问题,请随时编辑此问题

4

1 回答 1

0

当您使用name.prototype.method = function() {}where name is an object 时,您正在处理 JavaScript 类。据我所知,许多 JavaScript 框架都使用它(也许 jQuery 也是)。我还没有听说过 JavaScript 类中的属性。

于 2013-07-21T08:41:25.837 回答