最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Create a global function in JavaScript - Stack Overflow

programmeradmin4浏览0评论

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

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

Localized.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 !== "plete" ) {
        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] 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 50 files and do Localized.get("something"); But then I don't even have the Localized object available in the web console. For example if you have jQuery you can do $ in the web console and you can do anything there.

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

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

Localized.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 !== "plete" ) {
        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] 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 50 files and do Localized.get("something"); But then I don't even have the Localized object available in the web console. For example if you have jQuery you can do $ in the web console and you can do anything there.

Share Improve this question asked Aug 16, 2013 at 21:47 AliAli 10.5k21 gold badges74 silver badges108 bronze badges 8
  • 1 Inside your module do something like window.Localized = Localized to make the module available globally. – Frank van Puffelen Commented Aug 16, 2013 at 21:49
  • 1 Where are you running this from? I would expect it to be global because of root.Localized = factory();. If it's not, then this this you're passing is not the global object. Are you running that from inside another function, maybe an IIFE or a document.ready handler? – bfavaretto Commented Aug 16, 2013 at 21:52
  • You mentioned you want to replicate how jQuery does it, so why not look at the jQuery source and see for yourself? If I remember correctly it's similar to what Frank said – yuvi Commented Aug 16, 2013 at 21:54
  • Look, it's available globally when I tried in jsfiddle: jsfiddle/GP3TG – bfavaretto Commented Aug 16, 2013 at 22:01
  • First of all, the file containing this function should be the in the header tag before any other script, and this function could simply return window.Localized = (root.Localized = factory()); . Second, you have to be sure that you do not override the variable window anywhere before the return. – dbf Commented Aug 16, 2013 at 22:02
 |  Show 3 more ments

2 Answers 2

Reset to default 2

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

(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';

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 console as well except I have to initialize that by doing Localized.ready(function(){}); then I can get it to work.

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

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

发布评论

评论列表(0)

  1. 暂无评论