user353949
user353949

Reputation: 81

Why does this JavaScript example point to the global object (Window)?

function F() {
    function C() { 
        return this;
    } 
    return C();
} 
var o = new F();

Upvotes: 3

Views: 162

Answers (4)

Rob
Rob

Reputation: 8187

function C() is not a method of F, what you need to do is something like this:

function F() {
    this.C = function() { 
        return this;
    } 
    return this.C();
} 
var o = new F();

Although that is a bit convoluted, when you could just do this to achieve the same thing:

function F() {}
var o = new F();

Upvotes: 2

Eloff
Eloff

Reputation: 21656

function F() { return this; } will also return window. So will var obj = this. It't the value of "this" whenever "this" has no other value.

Upvotes: 0

CharlesLeaf
CharlesLeaf

Reputation: 3201

C() is not a method of the f object. As in, you can't call o.C();. If that makes sense. and because you return the return value of C() instead of a new instance of C it returns the window object.

Upvotes: 0

VoteyDisciple
VoteyDisciple

Reputation: 37803

Break down the component elements.

Suppose you were to do this:

function C() {
    return this;
}
var o = C();

There is clearly no object context here, so this is window.

Wrapping that setup in a constructor doesn't change the fact that there isn't any object involved in the context of a straightforward call to C().

Upvotes: 7

Related Questions