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

2
  • 4
    Too bad I cannot vote comments down! Commented Oct 13, 2012 at 9:31
  • 1
    The question you linked to does not show anything regarding temp1: function() {alert("Inside 26"); }. Where do you get this from? This is invalid JavaScript. Commented Oct 13, 2012 at 9:47

2 Answers 2

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 />
Sign up to request clarification or add additional context in comments.

1 Comment

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.
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>

3 Comments

Why the downvote (apart from not fixing the horrible javascript pseudo protocol)
@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"); };
@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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.