使用严格不允许在节点.js中使用它

use strict not allow use of this in node.js

本文关键字:js 节点 不允许      更新时间:2023-09-26

在我的js文件中使用'use strict'语句后,它不允许我在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
    }
  }
}

这个和Javascript:

  1. 默认情况下,这将引用全局对象。(浏览器上的"窗口")
  2. 引用了调用对象示例:

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

    这将向您显示对象本身。

  3. 因此,当您这样做时:

    ...
    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 说:这个函数甚至不是一个对象属性或方法。由于它不是一个方法,它将指向全局对象并导致容易出错的开发。

如果您希望以这种特定方式使用代码。

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未定义,因为它不会在严格模式下自动框箱到对象。

首先,在严格模式下传递给函数的值不会强制成为对象(也称为"boxed")。对于普通函数,这始终是一个对象:如果使用对象值 this 调用,则提供的对象;值,带框,如果使用布尔值、字符串或数字调用 this;或全局对象(如果使用未定义或 null this 调用)。(使用调用、应用或绑定来指定特定的 this。自动装箱不仅会带来性能成本,而且在浏览器中公开全局对象也是一种安全隐患,因为全局对象提供了对"安全"JavaScript 环境必须限制的功能的访问。因此,对于严格模式函数,指定的 this 不会装箱到对象中,如果未指定,则将未定义

阅读更多 MDN