IIFE(立即调用的函数表达式)中的 Object.Prototype 方法和'Use Strict'



原始代码:

'use strict';
function GitJs(config) {
    var defaults = {
        inheriting: false,
        clientId: undefined,
        accessToken: undefined,
        baseUrl: 'https://api.github.com',
        mode: 'read'
    };
    this.config = $.extend(defaults, config);
}
/**
 * Gets the jQuery method that GitJs#generateApiRequest is going to use to send the ajax request.
 *
 * @param {string} httpVerb The HTTP verb that the request will use,
 * @return string
 */
GitJs.prototype.getCommandMethod = function (httpVerb) {
    var method = $.get;
    switch (httpVerb) {
    case 'GET':
        method = $.get;
        break;
    case 'POST':
        method = $.post;
        break;
    }
    return method;
};
...

新代码:

(function() {
'use strict';
    'use strict';
    function GitJs(config) {
        var defaults = {
            inheriting: false,
            clientId: undefined,
            accessToken: undefined,
            baseUrl: 'https://api.github.com',
            mode: 'read'
        };
        this.config = $.extend(defaults, config);
    }
    /**
     * Gets the jQuery method that GitJs#generateApiRequest is going to use to send the ajax request.
     *
     * @param {string} httpVerb The HTTP verb that the request will use,
     * @return string
     */
    GitJs.prototype.getCommandMethod = function (httpVerb) {
        var method = $.get;
        switch (httpVerb) {
        case 'GET':
            method = $.get;
            break;
        case 'POST':
            method = $.post;
            break;
        }
        return method;
    };
    ...
}());

正如这段代码一样,当我尝试:

var gitjs = new GitJs();

我被告知 GitJs 是未定义的

我到底在想什么:

  • 我不想把use strict放在每个方法里面。
  • 我希望我的代码在缩小并连接到另一个文件时能很好地运行。
  • 我想使用.prototype语法以便以后轻松继承(和代码清晰度)
  • 我不想创建一个全局var gitJs变量,因为它可能会被其他人的脚本覆盖。
  • 我假设用户将始终通过 new 关键字调用对象构造函数

为了记录在案,我知道我错了。大错特错。我似乎无法弄清楚我思维中的缺陷在哪里,我希望得到一些指导。

你的问题是 GitJS 现在是立即调用的函数的私有变量。不能在专用作用域中隐藏函数,同时使其公开可用。它们是相互排斥的目标。

因此,您需要通过窗口显式设置全局变量

var GitJS;
(function() {
    'use strict';
     GitJS = function(){ ... }
     ...
}());

或从 IIFE 内部返回导出的函数。

var ExportedGitJS = (function(){ //using a different name just to be clear...
    'use strict';
    var GitJS = function(){ ... }
    ...
    return GitJS;
}());

好吧,我撒谎了。您可以制作Javascript模块而不必依赖全局变量,但这通常意味着使用不同的模块创建约定和/或使用模块库。如果您对此感兴趣,我强烈建议您查看 http://requirejs.org/。

@missingno是正确的,但我必须补充一点,你离使用 RequireJS 或等效的加载器只有一步之遥。你对全局变量持怀疑态度是对的;如果你承诺在具有定义的依赖项的异步模块中运行所有 JavaScript,那么你可以简单地将 GitJs 构造函数返回到全局定义函数,然后在任何需要它的东西中都需要你的 GitJS 模块。

// using the global define function provided by an AMD loader
// assuming that jQuery has already been provided by the paths config
define(['jquery'],function($) {
    'use strict';
    var GitJS = function() { ... }
    return GitJS
});

关于提供一些指导,我不确定这听起来是否完全明显,但一种方法可以:

  • 不是在每个方法中都插入use strict杂注
  • 连接时不对其他源施加严格模式
  • 使用.prototype语法
  • 不需要全局var gitJs变量
  • 让用户通过 new 关键字调用对象构造函数

这就是:

/* Class constructor, public, globally available */
function GitJs(config) {
    'use strict'; /* You may want to drop this one */
    var defaults = {
        inheriting: false,
        clientId: undefined,
        accessToken: undefined,
        baseUrl: 'https://api.github.com',
        mode: 'read'
    };
    this.config = $.extend(defaults, config);
}
/* IIFE to wrap the *main* strict pragma */
(function () {
    'use strict';
    GitJs.prototype.getCommandMethod = function (httpVerb) {
        /* ... */
    };
    GitJs.prototype.someOtherMethod = function (someParam) {
        /* ... */
    };
})();
...
/* some other block */
... {
    var gitjs = new GitJs();
};

这是否部分回答了这个问题?

最新更新