Tin
Tin

Reputation: 719

Setting the this pointer while evaluating javascript

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?

Upvotes: 0

Views: 198

Answers (2)

WeakPointer
WeakPointer

Reputation: 3312

I think cleaner.

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

Upvotes: 0

Matt Ball
Matt Ball

Reputation: 359946

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

Upvotes: 2

Related Questions