为什么这个变量没有被初始化?

Cli*_*ote -1 javascript

<head>我的页面中,我这样做:

<script type="text/javascript" src="js/foo.js"></script>
<script type="text/javascript">
  console.log(foo.bar);
</script>
Run Code Online (Sandbox Code Playgroud)

代码foo.js:

var foo = function()
{
    this.bar = function()
    {
        console.log('here');
    }
}
Run Code Online (Sandbox Code Playgroud)

稍后在html文档中:

<a href="#" onclick="foo.bar();">Test</a>
Run Code Online (Sandbox Code Playgroud)

但是,如果我单击上面的链接,即使已包含foo.js,也表示函数未定义.此外,如果我这样做console.log(foo)只显示'function()'并console.log(foo.bar)显示undefined.为什么这样,为什么我不能访问该功能?

zer*_*kms 7

因为您尚未创建对象.这是运行代码的正确方法:

var foo = function()
{
    this.bar = function()
    {
        console.log('here');
    }
}

var instance = new foo();
instance.bar();
Run Code Online (Sandbox Code Playgroud)

http://jsfiddle.net/zerkms/wDaEn/

或者,您可以用另一种方式定义它:

var foo = {
    bar: function() {
        console.log('here');
    }
};

foo.bar();?
Run Code Online (Sandbox Code Playgroud)

http://jsfiddle.net/zerkms/wDaEn/1/