简体   繁体   中英

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>

当您要访问其名称包含在变量中的属性时,正确的格式为

r[$module].init();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM