Javascript pass eval variables

I have an eval function that should execute javascript from php. but I need to pass the element, so I can impose hints on the user of the link that I 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 the following method to pass the element $(this)

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

I get an undefined element error that is defined in globalEval(); how can i fix this?

+4
source share
2 answers

This is a defining problem because global evaluation does not invoke code in the same scope as the element variable. If you must use eval , although eval is evil , you will have to do it so that you can call your code in the right environment. One way to do this is to wrap it as an anonymous function that you give parameters to the selected environment variables.

for instance

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

This means that the src string is parsed but not called eval , as it returns an anonymous function. Then you call it passing your data, in this case element .

Test it with var element = document.body, src = 'console.log(element.tagName)'; and you will see its log "BODY" . Note that if you want to set global variables (or functions) this way, they must be specified as global explicitly ( window.foobar = ... ), or they will be GCd after the completion of the anonymous function.

+4
source

If all you want to do is set this 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 that you get what you expect; There is a lot of luggage that comes with a global valuation, some of which may surprise you. It is best to avoid this if you do not need it.

Now, if you really wanted to call it element , a function constructor can do this as well:

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

All Articles