0

我正在开发一个简短的 JavaScript 程序,只有当我在特定位置注入任何琐碎的语句(例如 var asd;)时,它才能完美运行。该程序旨在演示一种简单的封装技术。

没有其他位置工作。任何琐碎的陈述都有效。这不是 DOM 加载问题,因为我什至不处理 DOM。

有效的版本:(警告,3 个警报) http://jsfiddle.net/bZUm6/3/

不工作的版本:http: //jsfiddle.net/bZUm6/2/

请注意“var asd;” 在第一个版本中。

有人可以告诉我为什么吗?我真的很感激。

最大限度

4

5 回答 5

5

破坏它的是分号删除。

即使你改变它也会起作用......

var asd;

简单到这个……

;

原因是下一行代码以 开头(,恰好是用它的结尾包装了一个函数)

这被解释为函数调用运算符,并试图调用前一个表达式。

    MyApp.util.toXML = function(options, obj) {
        // your code

        return result.join("");
    }

//    var asd;   // removing the semicolon

//  |------seen as invoking the result of the previous expression and passing
//  v         the function as an argument. 
    (function(toXML) {

        // your code

    })(MyApp.util.toXML);
//     ^---------------^ This is then attempting to invoke the return value
//     of "toXML", which if it successfully returned, returned a String, which 
//     can't be invoked.
于 2012-04-12T01:10:19.783 回答
2

当你这样做

MyApp.util.toXML = function(options, obj) {
}

(function(){
}());

你实际上是在调用函数

MyApp.util.toXML = function(options, obj) {
}( function(){}()) );
于 2012-04-12T01:11:57.407 回答
0

您忘记;了函数定义之后

MyApp.util.toXML = function() {
 // code
}; // this semicolon
于 2012-04-12T01:12:17.000 回答
0

你忘了分号,就是这样。请参阅http://jsfiddle.net/bZUm6/6/(工作)。

函数分配后,永远不要忘记;

于 2012-04-12T01:13:21.417 回答
0

http://jsfiddle.net/bZUm6/8/

您在函数后缺少分号。我想如果您不结束该语句,它会评估为其他内容。

于 2012-04-12T01:15:15.460 回答