在库外调用库的函数

时间:2014-12-09 21:41:37

标签: javascript

我有一个以(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

最常见的做法是什么?

3 个答案:

答案 0 :(得分:1)

这是你应该怎么做的。

&#13;
&#13;
var myApp = (function() {
  var stuff = []; //private

  return { //exposed to public
    myfunc: function(values) {
      alert('You said: ' + values);
    }
  }
}());

myApp.myfunc('Test Me');
&#13;
&#13;
&#13;

答案 1 :(得分:1)

您需要 Revealing Module Pattern

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.

在这种情况下,执行函数并返回一个Object(所以module现在是一个Object),你只需调用属于该对象成员的函数。

答案 2 :(得分:-1)

如果您的意思是全局可用,那么您可以将其分配给window对象:

window.myfunc = myfunc;

这就是Mixpanel的作用:

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