How do I set what "this" refers to?

58 views
Skip to first unread message

Glidos

unread,
May 2, 2012, 11:58:33 AM5/2/12
to v8-users
I need to run scripts that use a convention of "this" refering to a
specific, otherwise-unnamed object. Is there a way to make v8 handle
that convention?

So far the only work-around I can think of is to provide the global
template with an explicit property to refer to the object
(implicitThisObj say). Then I'd alter the incoming <script-text> to
be

implicitThisObj.tempFunc = function() { <script-text> };
implicitThisObj.tempFunc();

but that's a bit messy. Anyone know a better way?

Cheers,
Paul.

Andreas Rossberg

unread,
May 2, 2012, 12:07:52 PM5/2/12
to v8-u...@googlegroups.com
Rewrite to:

(function() { <script-text> }).call(implicitThisObj)

That's the easiest way. The global object is quite special, and cannot
just be replaced it with a random object.

/Andreas

Stephan Beal

unread,
May 2, 2012, 1:07:13 PM5/2/12
to v8-u...@googlegroups.com
On Wed, May 2, 2012 at 6:07 PM, Andreas Rossberg <ross...@google.com> wrote:
(function() { <script-text> }).call(implicitThisObj)

See also Function.apply(). The only difference between apply() and call() is how the 2nd+ argument(s) are passed to it:

myFunc.call( myObj, 1, 2 );
===
myFunc.apply( myObj, [1, 2] );

--
----- stephan beal
http://wanderinghorse.net/home/stephan/

Glidos

unread,
May 2, 2012, 6:13:17 PM5/2/12
to v8-users
Thanks. Both apply and call are improvements over my attempt, but
maybe I don't need any tricks:
if I just get v8 to execute <script-text> directly, will "this" refer
to the global object?

Ruben Rodriguez

unread,
May 2, 2012, 6:30:20 PM5/2/12
to v8-u...@googlegroups.com

Yes. The global object of the context within which you execute the script.

from my hacked android ;)

> --
> v8-users mailing list
> v8-u...@googlegroups.com
> http://groups.google.com/group/v8-users

Glidos

unread,
May 9, 2012, 10:02:56 AM5/9/12
to v8-users
Brilliant. That all works now. Thanks for the help.
Reply all
Reply to author
Forward
0 new messages