2

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?

Munawir
  • 3,346
  • 9
  • 33
  • 51
Moon
  • 22,195
  • 68
  • 188
  • 269

1 Answers1

8

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.

cliffs of insanity
  • 3,683
  • 1
  • 16
  • 18