Why is this JavaScript example pointing to a global object (window)?

function F() {
    function C() { 
        return this;
    } 
    return C();
} 
var o = new F();
+3
source share
4 answers

Break the component elements.

Suppose you were to do this:

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

There is clearly no context for the object, so thisthere is window.

The wrap around this setting in the constructor does not change the fact that in the context of a direct call, C()there is no object associated with C().

+7
source

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

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

Although this is a bit confusing when you could just do it to achieve the same:

function F() {}
var o = new F();
+2
source

C() f. , o.C();. . C() C, .

0

function F () {return this; } will also return a window. So it will be var obj = this. This value is "this" when "this" has no other meaning.

0
source

Source: https://habr.com/ru/post/1748014/


All Articles