1

After using 'use strict' statement in my js file it does not allow me to use javascript this after ist level

'use strict'

module.exports = {
  a: function() {
    var self = this //works fine upto this level
    var name = 'atul';
    function b() {
      this.name = name; //gives me error as can not set property name of undefined
    }
  }
}
Atul Agrawal
  • 1,474
  • 5
  • 22
  • 41

2 Answers2

1

this and Javascript:

  1. this references to the global object by default. ("window" on browsers)
  2. this references to the calling object example:

    var x = {name: "x", alphabet: function(){return this;}};
    x.alphabet(); // in this line, x is the calling object
    

    this will show you the object itself.

  3. So when you do:

    ...
    a: function() {
      var self = this //works fine upto this level
      var name = 'atul';
      function b() {
        this.name = name; //use strict is trying to tell you something
      }// you won't have a calling object for this function.
    }
    ...
    

use-strict says: this function is not even an object property or method. Since it's not a method it's this will point to the global object and lead to error prone development.

If you wish to use your code in this particular way.

module.exports = {
  a: {
       name: 'atul';
       b: function (name) {
         this.name = name; // now you have a as the property which can be called by an object a.
         //To be used as OBJECT.a.b();
    }
  };
};
Amresh Venugopal
  • 9,299
  • 5
  • 38
  • 52
-1

this is undefined as it is not autoboxed to an object in strict mode.

First, the value passed as this to a function in strict mode is not forced into being an object (a.k.a. "boxed"). For a normal function, this is always an object: either the provided object if called with an object-valued this; the value, boxed, if called with a Boolean, string, or number this; or the global object if called with an undefined or null this. (Use call, apply, or bind to specify a particular this.) Not only is automatic boxing a performance cost, but exposing the global object in browsers is a security hazard, because the global object provides access to functionality that "secure" JavaScript environments must restrict. Thus for a strict mode function, the specified this is not boxed into an object, and if unspecified, this will be undefined

Read more at MDN

avck
  • 3,535
  • 3
  • 26
  • 38
  • 1
    That means `'use strict' function test(){ console.log(this); } test(); // returns undefined new test(); // returns object` – Sami Apr 26 '16 at 08:35