简体   繁体   English

无法访问Javascript函数包装器中的函数?

[英]Cannot access functions inside Javascript function wrapper?

All, 所有,

My code was failing JSLint for the "use strict" issue. 我的代码因“严格使用”问题而使JSLint失败。 As suggested here : Disable "use the function form of use strict" but keep the "Missing 'use strict' statement" warning 如此处建议: 禁用“使用严格使用功能形式”,但保留“缺少'严格使用'语句”警告

If you wrap all the functions in the javascript file with another function wrapper, it will solve this issue. 如果使用另一个函数包装器将所有函数包装在javascript文件中,它将解决此问题。

However now after doing this all my functions are undefined when I call them from the page? 但是现在在执行此操作之后,当我从页面调用它们时,我的所有函数都未定义吗?

(function () {
"use strict";

/**
 * Update the page with a message informing the user
 * an email has been sent to their email address
 * @param details user details (email address)
 */
function shareEmailSent(details) {

    // unhide confirmation message
    $('strong#emailAddress').text(details.email);
    $('#confirmationMessage').removeClass('hide');
}

/**
 * Handle error
 */
function showError() {
    return false;
}

/**
 * Makes a POST request to send the current user
 * an email containing their unqiue share url
 * @param emailList
 */
function sendEmail(emailList) {
    var data = {};
    data.formToken = $('#formToken').val();
    data.emails = emailList;
    $.mooAjax({
        url: "/ajax/share/refer_a_friend_email.php",
        type: "POST",
        data: data,
        dataType: "json",
        error: showError,
        success: function (response) {
            shareEmailSent(response);
        }
    });
}
}());

eg 例如

shareEmailSent is not defined 未定义shareEmailSent

How can I fix this but also pass the JSLint issue as well? 我该如何解决这个问题,同时还要解决JSLint问题?

Thanks 谢谢

There are several approaches you can take. 您可以采取几种方法。 In descending order of niceness: 按照优美程度降序排列:

  1. Don't call the functions from outside. 不要从外部调用函数。 Bind all your event handlers using JavaScript (eg with addEventListener ) 使用JavaScript绑定所有事件处理程序(例如,使用addEventListener
  2. Use the revealing module pattern 使用显示模块模式
  3. Explicitly make functions globals (eg with window.someFunction = someFunction ). 显式地使函数成为全局变量(例如,使用window.someFunction = someFunction )。

Obviously, since sendEmail calls the other functions itself, it is probably the only one that would need to be exposed if you used the second or third approach. 显然,由于sendEmail本身会调用其他函数,因此如果使用第二种或第三种方法,则可能是唯一需要公开的函数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM