Moon Moon - 6 months ago 15
Javascript Question

using "use strict" and variable scope

I've started using

"use strict"
for my scripts recently. One of the behaviors I noticed is that this.
[name of variable]
doesn't work for an object. For example:

(function(){
"use strict";

window.person = {}
person.name = {
first: "first name",
last: this.first
}
}());


Seems like that strict js doesn't allow it anymore. Why is this removed? Are there any disadvantages?

Answer

In a function invoked without any implicit or explicit setting of the context, this becomes undefined.

If the outer context of your immediately invoked function is the global scope, and that's what you expected for its own context, you can use .call(this) to set its context to that of the outer context.

(function(){
    "use strict";

    window.person = {}
    person.name = {
        first: "first name",
        last: this.first
    }
}).call(this);

Irrespective of the strict/non-strict mode, this will never be a reference to the object being created using the literal notation. That's just how JavaScript works.