0

I use eval() to execute javascript that is returned by an ajax request from the server. However, I cant call a function that was created with eval() and got a ReferenceError: function is not defined.

Is it something normal that functions inside a javascript that was executed with eval() cannot be accessed? Is there a way to access such functions?

I think this simple jsFiddle illustrate the problem: http://jsfiddle.net/M2GLs/

5
  • Could you post a jsfiddle or sample code for this, I'm having difficultly understanding the problem. Thanks, Commented Jul 31, 2014 at 13:55
  • To answer your last question: every function can be accessed ;) Commented Jul 31, 2014 at 13:56
  • 1
    An ajax call within an eval of something returned from an ajax call? I'd seriously consider rethinking your architecture. Commented Jul 31, 2014 at 14:03
  • bonsaiden.github.io/JavaScript-Garden/#core.eval Commented Jul 31, 2014 at 14:10
  • @torazaburo well, its a full asynchrous app :P but your comment is correct! Commented Jul 31, 2014 at 14:15

1 Answer 1

1

The created function isn't in the correct scope. So your onclick can't 'see' it. Use

window.addFeatureToTable = function() { 
    // definition
}

to force it in the window-scope.

Working JsFiddle

To answer your question in the comment:

What you actualy have is something like this code:

function a()
{
    function b(where) {
        alert('b can be called inside a, but not outside, we are now ' + where);
    }
    b('inside');
}

a();
b('outside');

b is defined in the scope of a, and can only be accessed within this scope (demo). In your case the function-definition is within an eval, but the same rule aplies there. In that case within the scope of function(r). You can't access the scope of this function from within the a.onclick, so you have to change the function-definition. Alternatively you can bind the on-click just after the eval (jsFiddle), since it is then still in scope:

js = "function someFunction() { alert('function called') }"
eval(js)
document.getElementById('myA').onclick = someFunction;
Sign up to request clarification or add additional context in comments.

2 Comments

Thats the solution, can you elaborate why the function is not in the correct scope, in what scope is it? Is it possible to call the function specifying the right scope instead?
@BelowtheRadar - I answered your question with an edit (couldn't fit in a comment ;) )

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.