调用库外部的库函数

Call a function of a library, outside the library

本文关键字:库函数 外部 调用      更新时间:2023-09-26

我有一个以(function() { ... }) ();方案运行的库......

// mylibrary.js
(function() {
    function myfunc() { alert('hello'); };
    if (...) 
      return;
    // do something
}) ();

。我在 HTML 页面中使用的:

<!DOCTYPE html> 
<html lang="en"> 
<body>  
  <div>Bonjour</div>
  <script src="mylibrary.js"></script>
  <script>
    myfunc();  // scope error !
  </script>
</body>
</html>

如何在库外调用函数myfunc()我应该更改(function() { ... }) ();方案吗?(我曾经可以在图书馆内做一些return

最常见的做法是什么?

您需要揭示模块模式

var module = (function() { // Self invoking function
    var privateVariable = 42; // This variable is private to the module.
    var publicFunction = function() { console.log(42); } // Still not public
    return {
        myPublic: publicFunction // Now it is, notice optional the name change!
    }
})(); //Call itself.
module.myPublic(); // Call by the new name.

在这种情况下,执行函数并返回一个对象(因此module现在是一个对象),您只需调用作为该对象成员的函数。

这是你应该怎么做。

var myApp = (function() {
  var stuff = []; //private
  return { //exposed to public
    myfunc: function(values) {
      alert('You said: ' + values);
    }
  }
}());
myApp.myfunc('Test Me');

如果你的意思是让你的函数全局可用,那么你可以把它分配给window对象:

window.myfunc = myfunc;

这就是Mixpanel所做的:

http://cdn.mxpnl.com/libs/mixpanel-2-latest.js