On Fri, Feb 25, 2011 at 6:14 PM, mcot <[email protected]> wrote:
> I have some sample code below that generates a different result
> between browsers. I *think* chrome is doing the wrong thing, but I
> wanted to ask here first.
>
>
> function func(param) {
> console.log(param.x)
> }
>
> x = 100;
>
> // this is obv. 100
> console.log(this.x)
>
> var localObj = new function() { this.x = 90; }
>
> // this is obv. 90
> console.log(localObj.x)
>
>
> wrapper = function(st) {
> eval(st)
> }
>
> // this should be 90
> str = "func(this)"
> wrapper.apply(localObj, [str])
>
>
>
> neweval = eval; eval = undefined;
>
> wrapper = function(st) {
> neweval(st)
> }
>
> // this is 90 in firefox, but 100 in chrome...
> str = "func(this)"
> wrapper.apply(localObj, [str])
>
[...]
A simpler example — to understand what's going on — would be something like
this:
var x = 'outer';
(function() {
var x = 'inner';
(1,eval)('console.log(x + " " + this)');
}).call({ });
Note that (1,eval) is there to create a so-called indirect eval call —
similarly to `wrapper` function in your example, which, when called, is an
indirect eval call as well.
As you can see, Chrome 10 and FF4 both evaluate code in global scope and set
this binding to that of global object. Firefox 3.6, however, evaluates code
in global scope but sets `this` to whatever is referenced by `this` of a
calling scope (empty object in the above example).
Chrome and FF4 follow ES5 behavior. FF3.6 goes somewhat against ES3 and ES5
and does its own mish-mash: evaluates code in global scope (which is a
de-facto standard across majority of implementations; even during the times
of ES3) but sets `this` to that of calling scope — which is what direct eval
call would do.
--
kangax
--
To view archived discussions from the original JSMentors Mailman list:
http://www.mail-archive.com/[email protected]/
To search via a non-Google archive, visit here:
http://www.mail-archive.com/[email protected]/
To unsubscribe from this group, send email to
[email protected]