0

I want to execute some javascript which is part of html I download through AJAX. After downloading I call eval to all script tags. Is there a way to manipulate the this pointer and let it point to something I define (e.g. the AJAX blob that was downloaded). The reason why I need this is that I need some post-download processing on the HTML that was downloaded only. Now I do it by assigning an ID to the AJAX parent element and let the script do first a lookup (getElementById) of this element. This works as long as the ids are unique but that difficult to enforce in my case.

My current code looks like:

    if (element.children[i].tagName=="SCRIPT")
    {
        eval(element.children[i].innerHTML);
    }

I want the this pointer in innerHTML to point to element. Anyone?

Tin
  • 699
  • 1
  • 6
  • 19
  • I don't understand what is your question. "the `this` pointer in `innerHTML`" what does it means ? Can you put some simplified code (pseudo code?) to what you want to do (AJAX call, script evaluation etc), I think it would be more efficient than long text paragraphs :) – pomeh May 13 '12 at 17:55
  • have more context? not sure why you need the 'this' or 'eval'. Just including the – ltiong_sh May 13 '12 at 18:09
  • (1) I don't see why you need to `eval` anything. Append the ajax'd fragment to somewhere in the DOM and the browser will take care of this for you. (2) Why do you want to make `this` a reference to a ` – Matt Ball May 13 '12 at 18:14
  • If you download AJAX elements containing ` – Tin May 14 '12 at 04:23

2 Answers2

2

You can use Function.apply or Function.call. Note that primitives (42, true, "foo") will be boxed.

Matt Ball
  • 354,903
  • 100
  • 647
  • 710
  • Thanks for the quick answer. I had a quick look at `apply` and `call` but don't see how to use it in my case. I extended my question with my current code. Can you suggest how to change this code? Thx! – Tin May 13 '12 at 17:49
  • 1
    Okay, I found the solution! I first try calling `eval.apply(element,element.children[i].innerHTML)` but this didn't work. Now I changed the code to `var func = new Function(element.children[i].innerHTML); func.apply(element);` and this works fine! – Tin May 13 '12 at 18:14
  • That's exactly what I was going to suggest. See my comment on your question, however — this is all very very smelly. – Matt Ball May 13 '12 at 18:15
0

I think cleaner.

if (element.children[i].tagName=="SCRIPT")
{
    eval.call(element, element.children[i].innerHTML);
}
WeakPointer
  • 3,087
  • 27
  • 22