0

我得到了这个代码块:

(function($, exports) {
    var mod = function(includes) {
        if (includes) this.include(includes);
    };
    mod.fn = mod.prototype;
    mod.fn.proxy = function(func) {
        return $.proxy(func, this);
    };
    mod.fn.load = function(func) {
        $(this.proxy(func));
    };
    mod.fn.include = function(ob) {
        $.extend(this, ob);
    };
    exports.Controller = mod;

})(jQuery, window);

(function($, Controller) {
    mod = new Controller;
    mod.toggleClass = function(e) {
        this.view.toggleClass("over", e.data);
    };
    mod.load(function() {
        this.test = 'test';
        console.log(this.test); // Delayed
        this.view = $("#view");
    });

    console.log(mod.view) // returns undefined
    console.log(mod);

})(jQuery, Controller);

在firefox上执行时,firebug控制台面板上的结果如下:

undefined
Object { toggleClass=function(), proxy=function(), load=function(), more...}
test

这意味着最后两个日志函数(它们位于代码块的底部)在第一个函数之前执行(即:console.log(this.test); // 延迟)

你能解释一下为什么流程会以这种方式发生吗?

4

1 回答 1

2

你能解释一下为什么流程会以这种方式发生吗?

Because you set up the code in the function you passed into load to wait until DOM ready, by (inside your load function) passing a function reference into the jQuery $ function. When you pass it a function reference, that's a shortcut for $(document).ready(...). DOM ready doesn't happen until after your other code runs, so you don't see the output from the contents of the function you're passing into load until after your other outputs.

于 2012-12-28T07:48:31.940 回答