Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
168 views
in Technique[技术] by (71.8m points)

javascript - What happens if we set the value of undefined?

What does this line below do?

undefined = 'A value';

If it does not change the value of undefined then what happens behind the scenes?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

undefined is a property of the global object, i.e. it is a variable in global scope. The initial value of undefined is the primitive value undefined.

See 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:

  1. undefined = 'A value'; attempts to assign a string 'A value' to the global variable undefined
  2. In older browsers the value changes, i.e. undefined === 'A value'; // true. In newer browsers under strict mode the operation results in an error.

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

The value of undefined doesn't change in the above example. This is because (emphasis mine):

In modern browsers (JavaScript 1.8.5 / Firefox 4+), undefined is a non-configurable, non-writable property per the ECMAScript 5 specification.

Under strict mode:

'use strict';
undefined = true; // VM358:2 Uncaught TypeError: Cannot assign to read only property 'undefined' of object

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...