Just a learner
Just a learner

Reputation: 28572

In JavaScript, why non-existent "window" property values differ in these two situations?

I have a piece of JavaScript code:

var o = {
    name: "aaaa",
    f: function () {
        console.log(this);
        console.log(this.name);
    }
};

var m1 = o.f;
m1();

console.log(window.non_existent_property);

As I understand, the property name shouldn't matter too much. If I change the name of property name of object o to something like a everywhere, I should have the same result. However, this is not the case. See below image. I'm running the code on FireFox 75.0. Could anyone explain what is happening here please?

Upvotes: 0

Views: 41

Answers (1)

CertainPerformance
CertainPerformance

Reputation: 370699

The issue is not with the property of o in the object - the property name there is actually completely irrelevant, because you're losing the calling context when you assign the function to a standalone variable:

var m1 = o.f;
m1();

The above code means that m1 is called with no calling context, which means that this inside the m1 function will either be the global object (in sloppy mode), or undefined (in strict mode).

Since you're in sloppy mode, this.name references window.name, which is a reserved property that always exists on window and must always be a string. It defaults to the empty string.

Here's another snippet demonstrating the same sort of issue:

var foo = 'foo';
var o = {
    f: function () {
        console.log(this.foo);
    }
};

var m1 = o.f;
m1();

foo is a property of the window, since a global variable named foo was declared with var, so this.foo references window.foo.

Upvotes: 1

Related Questions