jQuery集合,功能和组织

mik*_*his 6 javascript jquery object

我有以下代码,它采用单个图像并应用特定的宽度:

function Foo ( img ) {
    this.image = img;
}
Foo.prototype._getWidth = function( ) {
    return this.image.data('largest') + 'px';
};
Foo.prototype.applyWidth = function(  ) {
    this.image.css( 'width', this._getWidth() );
};

var img = Foo( $('img') );

img.applyWidth();
Run Code Online (Sandbox Code Playgroud)

然而,我正在努力处理jQuery图像集合,例如$('img')没有for循环或$.each()每个函数内部(我有上面显示的这两个函数).

到目前为止,我提出的最好的是:

var temp = [];

function Create ( imgs ) {
    $.each( imgs, function( i ){
        temp[ i ] = new Foo ( $( this ) );
    });
    return temp;
}

Create( $('img') );

$.each( temp, function() {
    $(this).applyWidth();
}):
Run Code Online (Sandbox Code Playgroud)

这很好用,但感觉不整齐,感觉马虎.

最后,我想就以下内容提供一些指导.

  1. 理想情况下,我希望在命名空间下Theme.我想在Theme.Images使用模块模式下使用此方法.这可能吗?

  2. 如果在名称空间下,Theme.Images可以进行调用,例如Theme.Images.applyWidth()调用applyWidth()所有图像temp,请记住每个图像img都有一个唯一的值_getWidth().目前我相信我需要循环Theme.Images.temp并调用applyWidth()循环内部.

我真的开始欣赏javascript中的继承点,并希望继续使用它.

Nea*_*eal 1

var Theme = (function(){

    function Theme(images) {
        var _this = this;
        this.images = [];
        images.each(function(){
           _this.images.push(new Image(this))
        });
    }

    var Image = (function(){

        function Image(imageDOM) {
            this.image = $(imageDOM);
        }
        Image.prototype._getWidth = function( ) {
            return this.image.data('largest') + 'px';
        };
        Image.prototype.applyWidth = function(  ) {
            this.image.css( 'width', this._getWidth() );
        };

        return Image;

    })();

    Theme.prototype.applyWidth = function(){
        this.images.forEach(function(el){
            el.applyWidth();
        });
    }


    return Theme;

})();
Run Code Online (Sandbox Code Playgroud)

那么你可以这样做:

var MyTheme = new Theme($(some_selector));
MyTheme.applyWidth();
Run Code Online (Sandbox Code Playgroud)