Captain Giraffe
Captain Giraffe

Reputation: 14705

this in a global scope

the statement:

for( var item in this){
    console.log( item );
}

Is a noop in the global context. However in a function

function foo(){
    for( var item in this){
        console.log( item );
    }
}
foo();

This produces the global environment objects. What is the reason for this behaviour?

What is the syntax for accessing the objects currently in scope, as in the first sample?

Upvotes: 1

Views: 201

Answers (4)

Techniv
Techniv

Reputation: 1967

In JavaScript, "this" is not the current object but the running context of the current method.

For example :

function foo(){ 
   console.log(this);
}

In global context :

  • if I call foo(), the console log global
  • if I call setTimeout(foo, 0), the console log the Timer object because foo are call by the timer.

The best way to call your method are to use the call method of the Function object to bind yourself the running context when you call your method.

foo.call(this);

Sorry for my bad english. ^-^

Upvotes: 2

Paulo R.
Paulo R.

Reputation: 15609

The this is probably pointing to the exports object of node.

So in the first case, the this is right not to point at the window object. In the second case, well, the this is inside a function (which is not a method of an object) so, as you'd expect, it points back to the window.

Upvotes: 1

RobG
RobG

Reputation: 147363

ECMA-262 §10.4.1.1 shows that when entering a global execution context, this is set to the global object. So if the first code example is executed in a global context, this should reference the global object.

I don't have node.js, but if that is the host environment you should add a node.js tag to the question to attract someone who knows about node.js.

In the second example, the function's this is not set by the call, so it defaults to the global object. In strict mode, it will be undefined and attempting to access this will throw an error.

Upvotes: 1

Bergi
Bergi

Reputation: 664395

Have a look at MDN's introduction to the this keyword.

In the global scope, this refers to the global object.

In strict mode (which you seem not to have enabled) a simple function call leads to a undefined this-value.

For non-strict function (like your foo) a simple call leads to this being the global object again.

Upvotes: 1

Related Questions