我想在全局函数中安全地解析 this
的值,同时考虑是否通过 call
显式设置了 this
, apply
或 bind
函数。
在 NodeJS 中,以下似乎可以正常工作:
function checkThis() {
const defaultThis = require.main.children[0].exports;
console.log(this === defaultThis);
}
checkThis(); //=> true
checkThis.call(); //=> false
checkThis.apply(); //=> false
是否有可以在浏览器和 NodeJS 中运行的任何 JavaScript 通用替代方案?
最佳答案
也许你可以使用globalThis在浏览器领域。
The global globalThis property contains the global this value, which is akin to the global object.
请注意@Simon 的评论,您示例中的代码将无法在非严格模式下运行
关于javascript - 确定是否指定了 "this",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65405824/