The Global Object

本文深入探讨了JavaScript解释器启动时创建全局对象的过程及其意义。解释了声明全局变量实际上是定义全局对象属性的概念。
[size=medium]
When the JavaScript interpreter starts up, one of the first things it does, before executing any JavaScript code, is create a global object . The properties of this object are the global variables of JavaScript programs. When you declare a global JavaScript variable, what you are actually doing is defining a property of the global object.

[/size]
### 修复 `'this' must be of type nullish or must be the global object` 错误 在 JavaScript 中,`this` 的上下文在函数调用时由调用者决定。当使用 `Function.prototype.call()`、`Function.prototype.apply()` 或 `Reflect.apply()` 时,如果传入的 `this` 值不是 `null`、`undefined` 或全局对象(如 `window` 或 `globalThis`),则会抛出 `'this' must be of type nullish or must be the global object` 的错误[^2]。 --- ### 错误原因 JavaScript 强制要求 `call()` 和 `apply()` 的第一个参数必须是对象类型或 nullish 值。如果传入原始类型(如 `number`、`string`、`boolean`),则会抛出类型错误。例如: ```javascript function logThis() { console.log(this); } logThis.call(42); // TypeError: 'this' must be of type nullish or global object ``` 在非严格模式下,某些环境会尝试将原始值包装成对象(如 `new Number(42)`),但这种行为并不推荐且在严格模式下不会发生[^2]。 --- ### 解决方案 #### 1. 使用 `null` 或 `undefined` 如果函数逻辑不依赖 `this`,可以安全地传入 `null` 或 `undefined`: ```javascript function greet() { console.log('Hello'); } greet.call(null); // 正确 ``` #### 2. 使用对象包装原始值 若确实需要将原始值作为 `this` 上下文,应使用对应的包装对象: ```javascript function logThis() { console.log(this.valueOf()); } logThis.call(new Number(42)); // 正确 ``` #### 3. 使用全局对象作为 `this` 在某些需要访问全局上下文的场景中,可以传入 `globalThis`(浏览器中为 `window`,Node.js 中为 `global`): ```javascript function logGlobalContext() { console.log(this === globalThis); } logGlobalContext.call(globalThis); // 正确 ``` --- ### 注意事项 - 在严格模式下,JavaScript 不会自动将原始值转换为对象,因此传入非法值会直接抛出错误。 - 非严格模式下,虽然可能不会立即报错,但这种行为不可靠,建议始终传入合法的 `this` 值。 --- ###
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值