0

I am beginner to Javascript, Trying to access object function using variable name but its giving some error. this is just dummy code if some one can correct me what I am doing worng here.. What is best method to do it.

<html>
    <head>  
        <title>Pub/Sub Test</title> 
    </head>
    <body>  
        <div id="wrap1" data-components="tooltip">
            <p><h1>pubsubz Test</h1>
            <p>Run with Firebug or a console simulator open.</p></p>
        </div>
        <div id="wrap2" data-components="tooltip">
            <p><h1>pubsubz Test</h1>
            <p>Run with Firebug or a console simulator open.</p></p>
        </div>
        <div id="wrap3" data-components="tooltip">
            <p><h1>pubsubz Test</h1>
            <p>Run with Firebug or a console simulator open.</p></p>
        </div>

        <script type="text/javascript" src="jquery-1.6.4.min.js"></script>

        <script>
            var r=r||{};
            (function(tooltip,$,w,d,undefined){
                var pos,
                attr="data-options",
                defaultSetting = {
                    horizontal : true,
                    vertical : "above"
                };
                tooltip.init = function($el){
                    alert("hello");
                }
            })(r.tooltip = r.tooltip || {},jQuery,window,document);

            (function(r,$){
                var els = {
                    $body : $('body')
                };
                // identify modules
                var $modules = els.$body.find('[data-components]');
                // create queue from modules
                $modules.each(function(i,v){
                    var $module=$(this).data('components'); //value = tooltip
                    //want to excute r.tooltip.init() function but there is some error - $module contain value tooltip
                    r.$module.init();
                });
            })(r=r||{},jQuery);
        </script>
    </body>
</html>
Colin Brock
  • 21,267
  • 9
  • 46
  • 61
Nidhi
  • 201
  • 2
  • 6
  • 13
  • possible duplicate of [Use javascript variable in object name](http://stackoverflow.com/questions/1567278/use-javascript-variable-in-object-name) or [javascript object, access variable property name?](http://stackoverflow.com/questions/4255472/javascript-object-access-variable-property-name) or [Using a variable as part of a javascript object property](http://stackoverflow.com/questions/4773897/using-a-variable-as-part-of-a-javascript-object-property) – Matt Mar 16 '12 at 15:38
  • for dynamic values you can not access the property with dot notation, access the property as Jon has stated. – Ehtesham Mar 16 '12 at 15:42

1 Answers1

5

When you want to access a property whose name you have in a variable, the correct form is

r[$module].init();
Jon
  • 428,835
  • 81
  • 738
  • 806