简体   繁体   English

如何使我的JavaScript库具有全局性?

[英]How can I make my JavaScript library global?

I want to create a JavaScript library and have it readily available everywhere, exactly as Moment.js does. 我想创建一个JavaScript库,并使它随处可见,就像Moment.js一样。 For example, when I import Moment.js I can use it wherever I want by just typing: 例如,当我导入Moment.js时,只要键入以下内容,就可以在任何地方使用它:

moment.someMomentFunction()

Similarly, I'd want to call my function from everywhere by just doing: 同样,我想通过以下方法从任何地方调用我的函数:

mylib.function1()

mylib.function2()

etc.. 

Looking at the Moment.js source code I cannot see any reference to the window object (which is the one you should use if you want your object to be global) 查看Moment.js源代码,我看不到对window对象的任何引用(如果希望对象是全局对象,则应使用该引用)

EDIT: If you specifically want to create a library, export / import should help you: 编辑:如果您特别想创建一个库, 导出/导入应该可以帮助您:

import * as myModule from '/modules/my-module.js';

Export a function in the library with the export keyword: 使用export关键字在库中导出函数:

export function bing(Parameters here) {
alert("bong");
}

As answered in Calling a javascript function in another js file 在另一个js文件调用javascript函数所回答

You can only call functions from files that were loaded before and are in the same scope. 您只能从以前加载的文件和相同作用域的文件中调用函数。 If the accepted answer from the refered post doesn't work, try jQuery 如果从引用的帖子接受的答案不起作用,请尝试使用jQuery

$.getScript(url, function() { bläh(); });

Ordinary I use something like this to define a separate module using ES5. 普通的,我使用类似这样的东西来使用ES5定义一个单独的模块。

LibName= window.LibName || {};

LibName = function () {

  var yourVar1;
  var yourVar2;


  publicFunc1 = function() {

  };

  privateFunc2 = function() {

  };


  return {
    "publicFuncName" :  publicFunc1
  }

}();

With the help of ES6, you may create with class and without window variable. 在ES6的帮助下,您可以创建带类且不带窗口变量的对象。

class MyLib {
  constructor() {
    this.foo = 1;
    this.bar = 2;
  }

  myPublicMethod1() {
    return this.foo;
  }

  myPublicMethod2(foo) {
    return foo + this.bar;
  }
}

const instance = new MyLib();
export { instance as MyLib };

In code, you going to use it like this 在代码中,您将像这样使用它

import { MyLib } from './MyLib';

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

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