Nidhi
Nidhi

Reputation: 201

I am not able to access object function using variable name?

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>

Upvotes: 0

Views: 202

Answers (1)

Jon
Jon

Reputation: 437554

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

r[$module].init();

Upvotes: 5

Related Questions