0

i have a scenario where javascript function name needs to be decided at run time. For simplicity assume i have function name in javascript variable and now i want to create the function using variable value. I went thru the link Javascript - Variable in function name, possible? and tried the small code snippet

   <HTML>
       <HEAD>
          <TITLE> New Document </TITLE>
      </HEAD>
        <script>
        var temp1='at_26';
        temp1: function() {alert("Inside 26"); }
        </script>
         <BODY>
            <a href="javascript:window[at_26]()">Copy Text</a>
         </BODY>
    </HTML>

But when i click on hyperlink Copy Text it gives error saying Line: 1 Error: 'at_26' is undefined

Community
  • 1
  • 1
M Sach
  • 33,416
  • 76
  • 221
  • 314

2 Answers2

2

DEMOs

var temp1='at_26'; 
window[temp1]=function() {alert("Inside 26"); return false} 

and then

<a href="#" onclick="return window['at_26']()">Click</a>

or

<a href="#" onclick="return at_26()">Click</a>

should work

What I THINK you want since it does not pollute the global scope and is using a colon like in your example is this:

var myScope = {
  "at_26":function() {alert("Inside 26"); return false}
}

using

<a href="#" onclick="return myScope.at_26()">Click</a><br />
mplungjan
  • 169,008
  • 28
  • 173
  • 236
  • 1
    Yes, it is. `window[temp1]` resolves as `window['at_26']`, and the function is assigned there. Nowhere do you say `window['temp1'] = function` or `temp1 = function`. – Quentin Oct 13 '12 at 09:42
1

There were multiple issues in your code. A corrected version will be like:

<script>
    window['at_26'] = function() {alert("Inside 26"); };
</script>
<BODY>
    <a href="javascript:window['at_26']()">Copy Text</a>
</BODY>
techfoobar
  • 65,616
  • 14
  • 114
  • 135
  • 1
    Why the downvote (apart from not fixing the horrible javascript pseudo protocol) – mplungjan Oct 13 '12 at 09:29
  • @techfoobar my question is creating the function name with variable name.you have hardcoded the function name with window['at_26'] = function() {alert("Inside 26"); }; – M Sach Oct 13 '12 at 09:44
  • @MSach: You can almost always replace any literal with a variable. If `var a = 'at_26';` then you can write `window[a] = ...;` and `window[a]();`. No big deal. – Felix Kling Oct 13 '12 at 09:48