【问题标题】:What are the rules for strict mode changes?严格模式更改的规则是什么?
【发布时间】:2015-12-10 09:09:14
【问题描述】:

我有几个 Node JS 模块,有些使用 strict mode,有些不使用。

从严格模式模块调用到非严格模式模块时模式如何变化?在这样的通话过程中模式如何变化?

反之亦然,从非严格模式模块调用严格模式模块中的方法时,改变模式的逻辑是什么?

更改严格模式的一般规则是什么,特别是对于 NodeJS 而言?它是如何工作的?

【问题讨论】:

  • 我想你可以在这里stackoverflow.com/questions/18417381/…获得你的部分答案
  • @brielga 只是关于什么是严格模式,而不是关于它如何在上下文中发生变化,这是我想要理解的。

标签: javascript node.js


【解决方案1】:

无论从何种模式调用代码,都会以编写代码的模式解析、编译(在相关的情况下)和执行代码。唯一一次可以跨越两种模式的界限是在调用函数时,这就提出了一个问题,哪种模式用于完成调用的工作? (因为严格模式会影响调用函数的几个方面。)答案是:被调用函数的模式。所以当松散函数调用严格函数时,使用函数调用的严格规则;当一个严格的函数调用一个宽松的函数时,就会使用函数调用的宽松规则。

当您调用函数时,严格模式会以多种方式发挥作用:

  1. 在严格模式下,调用可以指定this为非对象值;在松散模式下,任何非对象都被强制为对象。
  2. 在严格模式下,未指定的调用(例如:foo())的默认thisundefined,而不是松散模式下的全局对象。
  3. 在严格模式下,被调用函数的arguments 对象具有callercallee 属性,在访问时会抛出TypeError;在松散模式下,规范将arguments.callee 定义为对被调用函数的引用;规范中没有arguments.caller,但一些实现提供了对其调用函数的引用。
  4. 事实上,在严格模式代码中,针对arguments 的特定于实现的扩展(如caller)是被禁止的,而在松散模式下它们是被允许的。
  5. 调用创建的供被调用函数使用的 arguments 对象在严格模式下与函数的命名参数完全解除关联,而不是像在松散模式下那样动态链接到它们。

这是一个调用严格函数的松散函数的示例,反之亦然,表明它是函数的规则调用是遵循的规则:

// Loose calling strict
const strictFunction1 = (function() {
  "use strict";
  return function(a, b) {
    console.log("=== strict function called:");
    console.log("#1 and #2", typeof this); // undefined
    console.log("#2", this === window); // false
    try {
      const x = arguments.callee;
      console.log("#3", "result of trying to access `arguments.callee`: got a " + typeof x);
    } catch (e) {
      console.log("#3", "result of trying to access `arguments.callee`: " + e.message);
    }
    // #5:
    a = 42; // Setting 'a'
    console.log("#5", a === arguments[0]); // false
  };
})();
function looseFunction1() {
  strictFunction1(67);
}
looseFunction1();

// Strict calling loose
const looseFunction2 = (function() {
  return function(a, b) {
    console.log("=== loose function called:");
    console.log("#1 and #2", typeof this); // object
    console.log("#2", this === window); // true
    try {
      const x = arguments.callee;
      console.log("#3", "result of trying to access `arguments.callee`: got a " + typeof x);
    } catch (e) {
      console.log("#3", "result of trying to access `arguments.callee`: " + e.message);
    }
    // #5:
    a = 42; // Setting 'a'
    console.log("#5", a === arguments[0]); // true
  };
})();
function strictFunction2() {
  looseFunction2(67);
}
strictFunction2();
.as-console-wrapper {
  max-height: 100% !important;
}

【讨论】:

    猜你喜欢
    • 2020-03-22
    • 2011-03-09
    • 1970-01-01
    • 2019-05-26
    • 2022-12-22
    • 2012-01-28
    • 2019-11-14
    • 1970-01-01
    相关资源
    最近更新 更多