javascript - 原型(prototype)对象的正确架构

标签 javascript architecture prototypejs

由于您无法访问 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();

这是 fiddle : http://jsfiddle.net/Ua6Mp/embedded/result/

问题:这是对原型(prototype)方法的适当利用吗?如果不是,扩展对同级方法属性的访问的约定是什么?

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

最佳答案

当您使用 name.prototype.method = function() {} 时,其中 name 是您正在处理 JavaScript 类的对象。据我所知,许多 JavaScript 框架都使用这个(也许 jQuery 也是如此)。我还没有听说过 JavaScript 类中的属性。

关于javascript - 原型(prototype)对象的正确架构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17769997/

相关文章:

javascript - prototype 和jQuery 和平共处?

javascript - 如何将 R Shiny 中的事件发送到 Google Analytics?

javascript - 添加事件类菜单不起作用

javascript - 将 JSON.parse() 返回类型转换为对象数组

javascript - 尝试编写渐变创建器 javascript 和 jquery

javascript - 这段 Javascript 代码片段可以通过 jQuery 进一步简化吗?

architecture - RESTful API 排序困境

python - 精心设计的 Python 应用程序的开源示例

caching - 在数据库和 redis 缓存之间同步数据的最佳策略是什么

javascript - Scriptaculous/Prototype 模态窗口