javascript匿名函数:为什么我的脚本不起作用

时间:2012-01-30 17:31:54

标签: javascript

我想尝试lib ala jquery,但我不明白为什么我的方法getUrl不输出任何内容,是吗?

mylib.js

    (function () {

    var scripts = document.getElementsByTagName('script');
    var index = scripts.length - 1;
    var thisScript = scripts[index];

    var myLib = {       
        getUrl: function() {
            return thisScript;
        }               
    }
}

if (!window.$$) {window.$$ = myLib}

)();

和mytest.html

<html>
<head>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.0/jquery.js"></script>
    <script src="mylib.js" type=text/javascript></script>
</head>

<body>
    <DIV id=url>url</DIV>   
    <script>
    var url = $$.getUrl();
    jQuery("#url").html(url);
    </script>
</body>
</html>

1 个答案:

答案 0 :(得分:5)

您的代码错位}

(function() {
    var scripts = document.getElementsByTagName('script');
    var index = scripts.length - 1;
    var thisScript = scripts[index];

    var myLib = {       
        getUrl: function() {
            return thisScript;
        }               
    };
//} <-- Remove this. 

  if (!window.$$) {window.$$ = myLib;}
} // <-- Add this, the closing brace of the anonymous function
)();