Two different x values ​​in javascript

Why does the first warning show 3 and the second warning show 1? I understand that thischanges the scope, but does not go(), and foo.baz.bar()is the same thing?

var x = 3;

var foo = {
    x: 2,
    baz: {
        x: 1,
        bar: function() {
            return this.x;
        }
    }
}

var go = foo.baz.bar;

alert(go());
alert(foo.baz.bar());
+4
source share
2 answers

The execution context of the first warning is a Window object. The execution context of the second warning is a function called bar. It. The execution context is a bit to understand.

Here are the details: https://tc39.imtqy.com/ecma262/#sec-execution-contexts

+1
source

JavaScript this . , , , , foo.baz.bar. go

function() {
   return this.x;
}

, foo. window global ( dev).

+1

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


All Articles