The variable defines but does not work in javascript as long as it presents the window

I have a small code snippet below

var foo = {
    bar: function () {
        return this.baz;
    },
    baz: 1
};
(function () {
    return typeof arguments[0]();
})(foo.bar);
baz = 1;
//result undefined

when the function is executed foo.bar, it thisrefers to the region of the window, which, of course, knows nothing about baz, so I defined baz=1in the window. but the program still does not work and returns undefined. why it returns undefined, but bazdetermined in the window, and I execute foo.bar from the window

+4
source share
3 answers

When you execute a type function arguments[0](), then it thisrefers to an object argumentsthat does not have a property baz, so it will still be undefined.

this :

arguments[0].call(foo) arguments[0].apply(foo).

+7

"this" . , foo.baz,

0

foo.bazwill work, but not this.baz. try reading areas in javascript

-1
source

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


All Articles