pmi*_*nda 61 javascript typeof
在现代浏览器(JavaScript 1.8.5 / Firefox 4+)中,根据 ECMAScript 5 规范, undefined 是不可配置、不可写的属性。即使情况并非如此,也要避免覆盖它。
undefined 的属性之一是不可写。
但如果我这样做:
var undefined = 'hello';
var test = undefined;
console.log(typeof test);
//stringRun Code Online (Sandbox Code Playgroud)
这是否意味着我可以覆盖 的值undefined?如果有人这样做会发生什么?JavaScript 应该对此发出警告吗?
jon*_*ano 52
Amy删除的评论给出了解决方案。您正在创建一个名为 的变量undefined,如果您在全局范围内执行代码段,则它不起作用:
var undefined = 'hello';
var test = undefined;
console.log(typeof test);Run Code Online (Sandbox Code Playgroud)
但是,如果您在undefined不再引用全局变量的本地范围内执行此操作,它会有效地工作:
(()=>{
var undefined = 'hello';
var test = undefined;
console.log(typeof test);
})()Run Code Online (Sandbox Code Playgroud)
为了防止这个错误,你可以使用'use strict';指令:
'use strict';
var undefined = 'hello';
var test = undefined;
console.log(typeof test);Run Code Online (Sandbox Code Playgroud)
如果您编写的代码无法控制在哪里执行(例如库、嵌入等),那么使用 IIFE 是一个很好的模式,它可以保证 undefined 始终正确/可用。下面是一个例子:
(function(undefined){
// undefined will equal `undefined` because we didn't pass in an argument to the IIFE
console.log(undefined); // always `undefined`, even if undefined !== `undefined`outside of the IIFE scope
})(); // No argument suppliedRun Code Online (Sandbox Code Playgroud)
我所有的测试都是在 Ubuntu 上使用 Firefox 72.0b10(64 位)进行的,第一个片段的结果在旧浏览器上可能会有所不同。
koo*_*oos 18
虽然可以将它用作全局作用域以外的任何作用域中的标识符(变量名)(因为 undefined 不是保留字),但这样做是一个非常糟糕的主意,它将使您的代码难以维护和调试。
来源https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/undefined
undefined是不保留因此可以为其分配一个新的值。
当您不使用时,strict mode您实际上是在创建一个undefined在本地范围内调用的变量并string为其分配一个值。
undefined是全局对象的属性。undefined 的初始值是原始值undefined。
use strict 将有助于在全局范围内防止此错误,同时它仍然可以在本地范围内被覆盖。
如果你想更安全,你应该使用void 0而不是undefined
which always returns undefined。
'use strict'
const test = (() => {
let undefined = "test"
console.log(typeof undefined)
console.log(typeof void 0)
})()Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2471 次 |
| 最近记录: |