简体   繁体   中英

How to access javascript function in the eval() scope

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/

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;

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