在node.js中严格使用这个不允许使用这个

在我的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.ab(); } }; }; 

this是未定义的,因为它不是自动绑定到严格模式的对象。

首先,以严格模式传递给一个函数的值不会被强制为一个对象(又名“boxed”)。 对于一个正常的函数,这总是一个对象:要么提供的对象,如果用一个对象值this来调用; 如果使用布尔值,string或数字调用该值,则装箱; 或全局对象,如果调用一个undefined或null这个。 (使用调用,应用或绑定来指定一个特定的事情。)不仅是自动装箱性能成本,而且在浏览器中暴露全局对象也是一个安全隐患,因为全局对象提供对“安全”JavaScript环境的function的访问必须限制。 因此,对于一个严格的模式函数,指定的这个没有被装入一个对象中,如果没有指定,这将是未定义的

阅读更多在MDN