我有几个Node模块,一些使用strict mode,另一些不使用。
当从严格模式模块调用到非严格模式模块时,模式是如何改变的?在这样的呼叫过程中,模式是如何改变的?
反之亦然,当从非严格模式模块调用严格模式模块中的方法时,更改模式的逻辑是什么?
更改严格模式的一般规则是什么,特别是NodeJS的规则是什么?它怎麽工作?
发布于 2017-04-03 15:16:25
无论代码是从哪种模式调用的,代码都会以编写时的模式进行解析、编译(在适当的情况下)和执行。唯一可以跨越这两种模式之间边界的时候是调用函数时,这就提出了一个问题:使用哪种模式来执行调用的工作?(因为严格模式会影响调用函数的几个方面。)答案是:被调用的函数的模式。因此,当一个松散函数调用一个严格函数时,将使用严格的函数调用规则;当一个严格函数调用一个松散函数时,将使用函数调用的宽松规则。
调用函数时,严格模式通过以下几种方式发挥作用:
this为非对象值;在宽松模式下,任何非对象都被强制为对象。this (例如:foo())是undefined,而不是处于宽松模式下的全局对象。arguments对象具有在访问时抛出TypeError的caller和callee属性;在松散模式下,规范将arguments.callee定义为对被调用函数的引用;规范中没有arguments.caller,但某些实现提供了对其上调用函数的引用。arguments进行特定于实现的扩展(如caller),而在松散模式下则允许它们。arguments对象在严格模式下与函数的命名参数完全分离,而不是在松散模式下动态链接到它们。<代码>H223<代码>G224下面是一个松散函数调用严格函数的示例,反之亦然,说明被调用的函数的规则是遵循的:
// 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;
}
https://stackoverflow.com/questions/32563558
复制相似问题