-3

I thought this was suppose to trigger a bug when calling a function from within a function using the keyword this. Running Chrome 37.0

S = function () {
    this.x = "test";
    this.test1 = function () {
        console.log("test1");
        this.test2();
    };
    this.test2 = function () {
        console.log(this); // output is s object, thought 'this' suppose to be global?
        console.log("test2");
    };
};
s = new S();
s.test1();

Edit:

I mixed it up with this code:

   s = function () {
            console.log(this);
            var t = function () {

                console.log(this);
            };
           t();


    };
  x = new s();
runners3431
  • 1,375
  • 11
  • 26

1 Answers1

1

Calling a function as part of an expression where you get the function reference from an object property calls the function with this set to the object you got the property from.

So your code:

s.test1();

...will call test1 setting this equal to the object referenced by s, because the call is part of an expression getting the test1 function reference from a property on the object s refers to.

Then in test1, when you do:

this.test2();

...it calls test2 setting this equal to the object referenced by this, because the call is part of an expression getting the test2 function reference from a property on the object this refers to.

Where you'd run into a problem with this not being set correctly would be if you didn't call test1 or test2 via an object property, like this:

var f = s.test1;
f();

Then, within the call to test1, this would be the global object (in loose mode) or undefined (in strict mode). The same sort of thing happens when passing a function as an argument:

foo(s.test1);

If foo calls the function its first argument relates to, we get the same thing (this = global object or undefined).

Since you're not doing that, though, that doesn't happen.

The key thing here is how the function is called, not where it's defined (inside another function or not).


More on this in How Does The this Keyword Work? here on SO, and in Mythical methods and You must remember this on my blog.

Community
  • 1
  • 1
T.J. Crowder
  • 879,024
  • 165
  • 1,615
  • 1,639