OO Javascript-适当的范围处理?

| 我已经写了一个简短且不完整的示例(出于这个问题),尝试使用jquery对一组图像的宽度求和。我在解决如何处理复杂的OO javascript应用程序中的范围时遇到了一些问题。
function imageContainer(){
      this.selector = \"img.inContainer\";

      this.width = function(){
        var tmp = 0;
        $(this.selector).each(function(){
          // use load to preload images
          $(this).load(function(){ 
             // our \'this\' pointer to the original object is long gone,
             // so is it even possible to accumulate a sum without using
             // globals? Ideally, I\'d like to increment a temporary value
             // that exists within the scope of this.width();
             tmp+=$(this).width();
          });
        });
        // I\'m thinking that returning here is problematic, because our
        // call to each() may not be complete?
        return tmp;
      }

      this.construct = function(){
        alert(this.width());
      }

      this.construct();
}
我并不是真的在寻找解决此问题的方法,我想知道这种事情应该怎么做-不会浪费封装的方式。我是否缺少明显的东西? 非常感谢。     
已邀请:
function imageContainer() {
    this.selector = \"img.inContainer\";

    this.width = function(cb) {
        var tmp = 0;
        var len = this.length;
        var count = 0;
        $(this.selector).each(function() {
            // use load to preload images
            var that = this;
            // load is ajax so it is async
            $(this).load(function() {
                tmp += $(that).width();
                if (++count === len) {
                    // counted all.
                    cb(tmp);
                }
            });
        });
    };

    this.construct = function(cb) {
        this.width(function(data) {
            alert(data);
        });
    };

    this.construct();
}
欢迎使用ajax。您异步并行执行一堆操作。因此,您需要跟踪完成的数量,并在所有完成后触发回调。 任何诸如“ 2”之类的异步操作都要求您阻塞100毫秒或更改API以使用回调。 而是使用
var that = this
模式,也可以改用
$.proxy
// load is ajax so it is async
$(this).load($.proxy(function() {
    tmp += $(this).width();
    if (++count === len) {
        // counted all.
        cb(tmp);
    }
}, this));
由于您具有在触发回调之前执行n个ajax任务的构造,因此可以使用一些糖概括一下。
this.width = function(cb) {
    // map all images to deferred objects, when deferred objects are resolved
    $.when($.makeArray($(this.selector).map(function() {
        var def = $.Deferred();
        $(this).load(function() {
            def.resolve();
        });
        return def;
    // then sum the widths and fire the callback.
    }))).then($.proxy(function(data) {
        var tmp = 0;
        $(this.selector).each(function() {
             tmp+=$(this).width();
        });
        cb(tmp);
    }, this));
};
请注意,我确实要使用
$.fn.reduce
,但它不存在。可能是
// reduce the set of images to the sum of their widths.
cb($(this.selector).reduce(0, function(memo, key, val) {
    return memo + $(this).width();
}));
再次考虑,这种糖并没有使其变得更简单,至少现在看起来更像是LISP,然后是C。     

要回复问题请先登录注册