为什么我不能引用我的匿名函数?

时间:2013-11-17 01:39:47

标签: javascript

我有以下js(内容概率不重要)

(function() {
   var module = {
      getAppAbsoluteUrl: getAppAbsoluteUrl,
      getAppRelativeUrl: getAppRelativeUrl,
      getAppODataApiUrl: getAppODataApiUrl
    };
    return module;

    function getAppAbsoluteUrl() {
        return _spPageContextInfo.webAbsoluteUrl;
    };

    function getAppRelativeUrl() {
        return _spPageContextInfo.webServerRelativeUrl;
    };

    function getAppODataApiUrl() {
        return getAppAbsoluteUrl() + "/_api";
    };
});

如果上面的代码在一个名为spAppUtils.js的文件中,而在另一个html页面中,我试着调用它,我得到一个未定义的消息。以上不是匿名函数吗?如何从其他页面初始化此功能?我试过引用js无济于事。我错过了什么?

由于

4 个答案:

答案 0 :(得分:1)

尝试做这样的事情:

var module = (function() {

    // move your functions before your return
    // hoisting (http://www.adequatelygood.com/JavaScript-Scoping-and-Hoisting.html) will allow you to add them after the return, but doesn't help readability and will likely confuse newcomers

    function getAppAbsoluteUrl() {
        return _spPageContextInfo.webAbsoluteUrl;
    };

    function getAppRelativeUrl() {
        return _spPageContextInfo.webServerRelativeUrl;
    };

    function getAppODataApiUrl() {
        return getAppAbsoluteUrl() + "/_api";
    };

    return { // explicitly export your public interface
        getAppAbsoluteUrl: getAppAbsoluteUrl,
        getAppRelativeUrl: getAppRelativeUrl,
        getAppODataApiUrl: getAppODataApiUrl,
        test: function () { alert('test') } 
    };
}()); // execute your anonymous function

module.test()

Fiddle

答案 1 :(得分:1)

要调用该函数,您需要在其后放置()

要捕获返回值(您在函数内分配给module然后返回的对象),您需要一个赋值运算符。

你可以摆脱整个函数的括号。它们只需要将函数声明转换为函数声明,因此您可以立即调用它,但是=(您需要)也可以这样做。

var myModule = function() {
// ...
}();

答案 2 :(得分:0)

这里有几个问题。首先,在定义所有内容之前返回函数是危险的。有一种称为变量提升的东西会自动将所有声明移到顶部,但我不确定它何时适用。

以下是无法访问代码的基本示例。

(function(){
  console.log("gets called");
  return;
  console.log("unreachable code");
})();

下一个问题是范围之一。

// window scope
(function(){
  // new scope
  var module = {"hello":"world"};
  console.log(module); // object
})();

console.log(module) // undefined

[edit]因此,为了使您的模块可以被其他脚本文件访问,您必须在窗口范围内为它定义一个全局变量。

(function(){
  window.module = {...}
})();

答案 3 :(得分:-1)

您可以尝试使用<script>标记将其直接插入到html中,以查看问题是函数本身还是指向.js文件的链接

相关问题