如果我们设置undefined的值会发生什么? [英] What happens if we set the value of undefined?
问题描述
下面这行是做什么的?
undefined = 'A value';
如果它没有改变 undefined
那么幕后会发生什么?
If it does not change the value of undefined
then what happens behind the scenes?
推荐答案
undefined
是属性全局对象,即它是全局范围内的变量。undefined
的初始值是原始值undefined
。
undefined
is a property of the global object, i.e. it is a variable in global scope. The initial value ofundefined
is the primitive valueundefined
.
请参阅 https: //developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/undefined
所以,它只是一个变量,没什么特别的。现在,回答你的问题:
So, it's just a variable, nothing special about it. Now, to answer your questions:
-
undefined ='值';
尝试将字符串'A值'
分配给全局变量undefined
- 在旧浏览器中,值会发生变化,即
undefined ==='A value'; // true
。在严格模式下的较新浏览器中,操作会导致错误。
undefined = 'A value';
attempts to assign a string'A value'
to the global variableundefined
- In older browsers the value changes, i.e.
undefined === 'A value'; // true
. In newer browsers under strict mode the operation results in an error.
您可以在浏览器控制台中测试以下内容(我在这里使用现代浏览器 - Google Chrome):
You can test the following in a browser console (I'm using a modern browser here - Google Chrome):
undefined = true;
console.log(undefined); // undefined
// in older browsers like the older Internet Explorer it would have logged true
在上面的示例中, undefined
的值不会改变。这是因为(强调我的):
The value of undefined
doesn't change in the above example. This is because (emphasis mine):
在现代浏览器(JavaScript 1.8.5 / Firefox 4+)中,undefined是根据ECMAScript 5规范,不可配置,不可写属性。
在严格模式下:
'use strict';
undefined = true; // VM358:2 Uncaught TypeError: Cannot assign to read only property 'undefined' of object
这篇关于如果我们设置undefined的值会发生什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!