javascript pass eval variables

与世无争的帅哥 提交于 2020-06-25 09:56:56

问题


i have eval function, which needs to execute javascript from php. but i need to pass element, so i can put mouse over tips on the link user clicked on.

var globalEval = function globalEval(src, element) {
        if (window.execScript) {
            window.execScript(src);
            return;
        }
        var fn = function(element) {
            window.eval.call(window,src);
        };
        fn(element);
    };

im using following way to pass $(this) element

globalEval(js_code, $(this));
// js_code is = alert(element);

i get error of undefined element, which is defined in globalEval(); how can i fix this?


回答1:


This is a scoping issue as the global eval isn't invoking the code in the same scope as the variable element. If you must use eval even though eval is evil, you'll have to do it in a way that lets you invoke your code in the environment you want. One way to do this is to wrap it as an anonymous function which you give parameters for the environment variables of choice.

For example

window.eval.call(window,'(function (element) {'+src+'})')(element);

This means the src string is parsed but not invoked by the eval as it returns an anonymous function. You then invoke it, passing your data, in this case element.

Test it with var element = document.body, src = 'console.log(element.tagName)'; and you'll see it log "BODY". Please note that if you want to set global variables (or functions) this way they have to be stated as global explicitly (window.foobar = ...) or they will be GCd after the anonymous function finishes.




回答2:


If all you want to do is have this set when you evaluate some code, try:

// Code you want to evaluate
var code = 'return this.whatever'

// What you want "this" bound to:
var that = { whatever: 69 }

// Now do this:
var result = new Function(code).call(that)

Using the Function constructor means you'll get what you expect; There is a lot of baggage that comes along with global eval, some of which might surprise you. Best to avoid it if you don't need it.

Now if you really wanted to call it element, the Function constructor can do that as well:

code = 'alert(element)'
var use_element = 69
result = new Function("element", code).call(this, use_element)


来源:https://stackoverflow.com/questions/13906161/javascript-pass-eval-variables

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!