use strict not allow use of this in node.js

使用后“使用严格”语句在我的JS文件不允许我之后IST级使用JavaScript 这个

'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
    }
  }
}

this and Javascript:

  • this references to the global object by default. ("window" on browsers)
  • 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.

  • 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();
        }
      };
    };
    

    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 (aka "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

    链接地址: http://www.djcxy.com/p/94908.html

    上一篇: Javascript这个关键字里面的函数

    下一篇: 严格禁止在node.js中使用这个