2013-05-27 141 views
-2

在脚本标记中,为了检索变量内部的变量值,我已经使用了下面的代码,但是它没有返回任何值。变量javascript中的变量

<script src="http://code.jquery.com/jquery-1.10.0.min.js"></script> 
    <script type="text/javascript" language="javascript"> 
    $(function() { 
     var data = { 
     GetAnimals: function() 
     { 
     return 'tiger';   assign value to GetAnimals variable 
     }, 
     GetBirds:function() 
     { 
     return 'pegion';  assign value to GetBirds variable 
     } 
     } 
     }); 

     document.write(data.GetAnimals);//should print tiger 
     document.write(data.GetAnimals);//should print pegion 

     </script> 

但是,我无法打印所需的结果。
在此先感谢。

+0

我猜'数据'有局部范围? – NINCOMPOOP

回答

4

你不调用功能功能:

document.write(data.GetAnimals());//should print tiger 
document.write(data.GetBirds());//should print pegion 

最重要的是,你要访问data$(function() { ... });,其中到那个时候已经不存在了。

$(function() { 
    var data = { 
     GetAnimals: function() { 
     return 'tiger'; //  assign value to GetAnimals variable 
     }, 
     GetBirds:function() { 
     return 'pegion'; //  assign value to GetBirds variable 
     } 
    } 

    document.write(data.GetAnimals());//should print tiger 
    document.write(data.GetBirds());//should print pegion 
    }); 

Demo

+0

即使通过使用建议的调用功能,结果是没有获得.. –

+0

@BharathKumar它的工作完美检查在这里http://jsfiddle.net/rMc8n/ – sachin

+0

@sachin谢谢,你是正确的,但当代码包括jquey它不工作。我想用它包含在我的上下文中的jQuery中。 –

1

从来没有听说过 “自我调用的函数”?

var data = { 
    GetAnimals: (function() { 
      return 'tiger'; 
      // assign value to GetAnimals variable 
     })(), 
    GetBirds: (function() { 
      return 'pegion'; 
      // assign value to GetBirds variable 
     })() 
} 
}); 
0
$(function() { 
    var data = { 
     getAnimals: function() { 
      return 'tiger'; 
     }, 

     getBirds: function() { 
      return 'pigeon'; // I guess you meant pigeon 
     } 
    } 
    }); 

    document.write(data.getAnimals()); // *call* the method 
    document.write(data.getBirds()); // call the correct method 

,并请使用正确的大写和缩进。