gpt4 book ai didi

javascript - 严格模式变更的规则是什么?

转载 作者:太空宇宙 更新时间:2023-11-03 22:33:56 25 4
gpt4 key购买 nike

我有几个 Node JS 模块,其中一些使用严格模式,其他则不使用。

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

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

更改严格模式(尤其是 NodeJS)的规则是什么?它是如何工作的?

最佳答案

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

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

  1. 在严格模式下,调用可以指定 this是一个非对象值;在松散模式下,任何非对象都被强制为对象。
  2. 在严格模式下,默认 this对于未指定它的调用(例如: foo() )是 undefined而不是松散模式下的全局对象。
  3. 在严格模式下,被调用函数的arguments对象有callercallee抛出 TypeError 的属性访问时;在松散模式下,规范定义 arguments.callee作为被调用函数的引用;没有arguments.caller在规范中,但某些实现提供了对其调用函数的引用。
  4. 事实上,在严格模式代码中,特定于实现的扩展(如 caller )到 arguments是被禁止的,而在宽松模式下是允许的。
  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;
}

关于javascript - 严格模式变更的规则是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32563558/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com