Why does undefined behave differently than other variables?

I am using Google Chrome 16.0.912.63 and have the following code:

__defineGetter__('x', function(){ console.log('In Getter: x'); return 1; }); __defineGetter__('undefined', function(){ console.log('In Getter: undefined'); return 2; }); console.log(x); console.log(undefined); 

The getter function for x is entered correctly, but the getter for undefined is never entered. Output to my console:

 In Getter: x 1 undefined 

It always seemed to me that undefined behaves just like any other global variable. I know statements like

 undefined = 10; undefined = null; undefined = 'defined'; 

Are they all valid, so it differs from undefined , which makes it impossible to get getter (at least in my browser).

Jsfiddle

+4
source share
2 answers

It doesn't behave like a normal variable, it just pretends to be, at least in Firefox and Chrome. Try:

 var x; undefined = "Hello!"; x === undefined; // true; undefined doesn't change 

This is more like the readonly property, but does not cause a writing error.

+3
source

It seems that __defineGetter__ just fails. Object.defineProperty gives an error message:

 redefine_disallowed 

when you call this in Chrome:

 Object.defineProperty(window, "undefined", { get: function() { return 2; } }); 

On the other hand:

 window.__defineGetter__("undefined", function() { return 2; }); window.__lookupGetter__("undefined"); // undefined, so __defineGetter__ just ignored call 

Why it works in the Chrome console:

When you define and get undefined at a time when you paste the code into the console, it works because some functions that use the with block referring to console._commandLineAPI are executed behind the scenes:

 if (injectCommandLineAPI && inspectedWindow.console) { inspectedWindow.console._commandLineAPI = new CommandLineAPI( this._commandLineAPIImpl, isEvalOnCallFrame ? object : null ); expression = "with ((window && window.console && window.console._commandLineAPI) || {}) {\n" + expression + "\n}"; } return evalFunction.call(object, expression); 

So you just define console._commandLineAPI.undefined .

Another point is that it overwrites console._commandLineAPI (see the code above), so it does not work if you define and receive undefined as two commands, since the getter was thrown by correspondence at the time of the attempt to get undefined .

This, as well as the fact that it does not overwrite window.undefined , most likely it works in the console.

+2
source

Source: https://habr.com/ru/post/1387903/


All Articles