在 JavaScript 中创建一个全局函数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18282610/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 11:20:22  来源:igfitidea点击:

Create a global function in JavaScript

javascriptfunction

提问by Ali

I'm trying to create a global function where I can use it anywhere inside a .jsfile.

我正在尝试创建一个全局函数,我可以在.js文件内的任何地方使用它。

We have more than 50 javascript files joined together and inside each files I want to be able to use this library anywhere.

我们有 50 多个 javascript 文件连接在一起,在每个文件中,我希望能够在任何地方使用这个库。

Localized.js

本地化.js

(function (root, factory) {
    if (typeof define === 'function' && define.amd) {
        // AMD. Register as an anonymous module.
        define(factory);
    } else if (typeof exports === 'object') {
        // Node. Does not work with strict CommonJS, but
        // only CommonJS-like enviroments that support module.exports,
        // like Node.
        module.exports = factory();
    } else {
        // Browser globals (root is window)
        if (typeof Localized !== 'undefined') {
            throw 'Localized" already in use';
        }

        root.Localized = factory();
    }
}(this, function () {

  var _strings,
      _readyCallback,
      _isReady = false,
      _requestedStrings = false;

  function ready( data ) {
     _readyCallback = _readyCallback || function(){};

    function domReady() {
      // If the DOM isn't ready yet, repeat when it is
      if ( document.readyState !== "complete" ) {
        document.onreadystatechange = domReady;
        return;
      }
      document.onreadystatechange = null;
      _strings = data;
      _isReady = true;
      _readyCallback();
    }

    domReady();
  }

  // Get the current lang from the document's HTML element, which the
  // server set when the page was first rendered. This saves us having
  // to pass extra locale info around on the URL.
  function getCurrentLang() {
    var html = document.querySelector( "html" );
    return html && html.lang ? html.lang : "en-US";
  }

  var Localized = {
    get: function( key ) {
      if ( !_strings ) {
        console.error( "[goggles.webmaker.org] Error: string catalog not found." );
        return "";
      }
      return ( _strings[ key ] || "" );
    },

    getCurrentLang: getCurrentLang,

    // Localized strings are ready
    ready: function( cb ) {
      if ( !_requestedStrings ) {
        _requestedStrings = true;
        _readyCallback = cb;

        function onload( data ) {
          ready( data );
        }
        onload.error = console.log;

        var xhr = new XMLHttpRequest();
        xhr.open('GET', '/strings/' + getCurrentLang() + '?bust=' + Date.now(), false);
        xhr.send(null);
        if (xhr.status !== 200) {
          err = new Error(id + ' HTTP status: ' + status);
          err.xhr = xhr;
          onload.error(err);
          return;
        }
        onload(JSON.parse(xhr.responseText));
      };
      if ( _isReady ) {
        _readyCallback();
      }
    },

    isReady: function() {
      return !!_isReady;
    }
  };
  return Localized;
}));

So I want to be able to go into any of the 50files and do Localized.get("something");But then I don't even have the Localizedobject available in the web console. For example if you have jQueryyou can do $in the web console and you can do anything there.

所以我希望能够进入50 个文件中的任何一个并执行Localized.get("something");但是我什至没有Localizedweb 控制台中可用的对象。例如,如果您拥有jQuery您可以$在 Web 控制台中执行的操作,并且您可以在其中执行任何操作。

采纳答案by Ali

So it turns out that my javascript is globally defined and accessible everywhere within the file that is included and it can be call from the consoleas well except I have to initialize that by doing Localized.ready(function(){});then I can get it to work.

所以事实证明我的 javascript 是全局定义的,并且可以在包含的文件中的任何地方访问它,它也可以从控制台调用,除非我必须通过这样做来初始化它,Localized.ready(function(){});然后我才能让它工作。

So if anyone is looking to create their own global function and make it standard they can follow this way.

因此,如果有人希望创建自己的全局函数并使其成为标准,他们可以遵循这种方式。

amdWeb.jsis what I use as a standard to create global function.

amdWeb.js是我用来创建全局函数的标准。

回答by FeaturedSpace

Have you ever looked at the Three.js global function? It's super easy to understand!

你有没有看过 Three.js 的全局函数?超级容易理解!

(function (global, factory) {
 typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
 typeof define === 'function' && define.amd ? define(['exports'], factory) :
 (factory((global.THREE = global.THREE || {})));
}(this, (function (exports) { 'use strict';