首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >严格模式更改的规则是什么?

严格模式更改的规则是什么?
EN

Stack Overflow用户
提问于 2015-09-14 19:23:09
回答 1查看 174关注 0票数 2

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

当从严格模式模块调用到非严格模式模块时,模式是如何改变的?在这样的呼叫过程中,模式是如何改变的?

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

更改严格模式的一般规则是什么,特别是NodeJS的规则是什么?它怎麽工作?

EN

回答 1

Stack Overflow用户

发布于 2017-04-03 15:16:25

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

调用函数时,严格模式通过以下几种方式发挥作用:

  1. 在严格模式下,调用可以指定this为非对象值;在宽松模式下,任何非对象都被强制为对象。
  2. 在严格模式下,未指定它的调用的默认this (例如:foo())是undefined,而不是处于宽松模式下的全局对象。
  3. 在严格模式下,被调用函数的arguments对象具有在访问时抛出TypeErrorcallercallee属性;在松散模式下,规范将arguments.callee定义为对被调用函数的引用;规范中没有arguments.caller,但某些实现提供了对其上调用函数的引用。
  4. 实际上,在严格模式代码中,禁止对arguments进行特定于实现的扩展(如caller),而在松散模式下则允许它们。
  5. 通过调用以供被调用函数使用的arguments对象在严格模式下与函数的命名参数完全分离,而不是在松散模式下动态链接到它们。<代码>H223<代码>G224

下面是一个松散函数调用严格函数的示例,反之亦然,说明被调用的函数的规则是遵循的:

代码语言:javascript
复制
// 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();
代码语言:javascript
复制
.as-console-wrapper {
  max-height: 100% !important;
}

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/32563558

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档