最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Why does the delete keyword act opposite to expected? - Stack Overflow

programmeradmin2浏览0评论

In Chrome, try the following in the console. First

console = 0;

to assign the value 0 to console. Then

console // (prints `0`)

to check we have correctly overwritten console. Finally,

delete console

Surprisingly, console now holds the original Console object. In effect, the delete keyword "resurected" console, instead of exterminating it!

Is this expected behaviour? Where is this implemented in the Chromium code?

In Chrome, try the following in the console. First

console = 0;

to assign the value 0 to console. Then

console // (prints `0`)

to check we have correctly overwritten console. Finally,

delete console

Surprisingly, console now holds the original Console object. In effect, the delete keyword "resurected" console, instead of exterminating it!

Is this expected behaviour? Where is this implemented in the Chromium code?

Share Improve this question edited Sep 1, 2012 at 18:28 Randomblue asked Sep 1, 2012 at 0:27 RandomblueRandomblue 116k150 gold badges362 silver badges557 bronze badges
Add a comment  | 

8 Answers 8

Reset to default 12 +50

As mentioned in MDN's documentation on delete:

If the delete operator succeeds, it removes the property from the object entirely, although this might reveal a similarly named property on a prototype of the object.

Your delete simply unshadows native property inherited through prototype chain.

Some browsers have window inherit from native prototype and you'll have check out sources to see how property is inherited, if you really want to know that much details, but mostly they work just like JS' own.

Got it:

I've managed to prove the console is a property of the global object: just open your console and type: this.parent or window.parent. This will show a more complete list of properties and methods at your disposal. Including console: Console, about 2/3 of the way down, just below chrome: Object (interesting...:)). I thought of this when I remembered that I somehow managed to change the CSS rules of the console itself (in chrome, don't ask me how I got there, I can't remember).
Bottom line: console ís a property of the window object. I think this backs up my explanation rather well.


@Randomblue: Since you're interested in how this is implemented in v8 you can check the trunk here, or browse the bleeding. Somewhere you'll find a test dir, that has a number of files that deal with delete. Special attention is given to delete used on global variables/properties: they can't be deleted, in other words: the console is never really gone. I would like to know why this answer went from being voted helpful and accepted to not-helpful and not-accepted, though...


It's perfectly simple. Console isn't some random, stand-alone, object. It's actually a property of the global object. Open your console and type this.console === console or window.console === console. It logs true, of course.

So thanks to implied globals console = 0 is pretty much the same as window.console = 0. You're sort of reassigning a property of an instance. The difference with normal objects is that the global object isn't just any old object: it's properties cannot be deleted (somewhere here on MDN). So your global is masking the console object, which is still there, you've just lost your reference too it:

var bar = window.console;
console = 12;
bar.log(console);//logs 12, bar is now an alternative reference to the console object
delete console;//unmasks the console reference
console === bar;//true

Don't, for a moment, be fooled into thinking the global object doesn't have a prototype. Just type this.constructor.name and lo and behold: Window with a capital W does appear. Another way of double checking is: Object.getPrototypeOf(this); or Object.getPrototypeOf(window);. In other words, there are prototypes to consider. Like always, the chain ends with Object.prototype:

 Object.getPrototypeOf(Object.getPrototypeOf(window));

In short, there is nothing weird going on here, but the weird nature of the global object itself. It behaves as if there is some form of prototypal inheritance going on. Look at the global object as though it were set up like this:

this.prototype.window = this;//<-- window is a circular reference, global obj has no name
this.prototype.console = new Console();//this is the global object
this.hasOwnProperty(console);//false
console = 0;//implied global

When attempting to access console, JS finds the property console you've just set prior to the instance of the Console object, and happily returns its value. The same happens when we delete it, the first occurance of console is deleted, but the property higher up the prototype chain remains unchanged. The next time console is requested, JS will scan the inheritance chain and return the console instance of old. The console-object was never really gone, it was merely hidden behind a property you set yourself.

Off topic, but for completeness' sake:
There are a few more things too it than this (scope scanning prior to object/prototype chain searching), due to the special character of the global object, but this is, AFAIK, the essence of it.
What you need to know is that there is no such thing (in JS) as an object without (at least) 1 prototype. That includes the global object. What you're doing merely augments the current global object's instance, delete a property and the prototype takes over again. Simple as that. That's what @Peeter hinted at with his answer: implied globals are not allowed in strict mode, because they modify the global object. Which, as I tried to explain here, is exactly what happens here.

Some properties of the window object aren't deletable. True is returned because you aren't running in strict mode. Try the following (not in console):

"use strict";
delete console;

and you will get an exception (JSFiddle).

You can read more about how this is handled at http://es5.github.com/#x11.4.1

First, this is not just the console, you can do this with every native property every browser-defined property on window.

setTimeout = 0;
setTimeout //=> 0
delete window.setTimeout;
setTimeout //=> function setTimeout() { [native code] }

Properties that are part of the ECMA-Script Spec can be fully overwritten & deleted:

Array = 0;
Array //=> 0
delete window.Array;
Array //=> ReferenceError

You can nearly overwrite any property on window, delete the overwrite and get back to the normal function.

The simple reason for this is that console and all the other native global functions browser defined properties are not linked to the DOMWindow Object via javascript but via C++. You can see the console being attached to the DOMWindow right here and the implementation of DOMWindow here

That also means that the window object is somehow a C++ Object masked as a javascript object the window object is at least partly defined by C++, and it is not prototypical inheritance doing the magic: Take for example:

window.hasOwnProperty('console') //=> true, console is defined directly on the window
window.__proto__.hasOwnProperty('console') // => false, the window prototype does not have a console property

Also, if it was prototypical inheritance, the following would lead to console returning 3:

window.__proto__.console = 3;
delete console;
console //=> still returns console;
window.hasOwnProperty('console') //=> the window still has it.

The same with a property respecting prototypical inheritance:

window.someProp = 4;
window.__proto__.someProp = 6;
someProp //=> 4
delete someProp;
someProp //=> 6

Therefore, when you set console to anything, it is gone and can only be resurrected by (hoorray for the irony): delete console.

So, what it means is that you cannot delete any native properties on the window object. Try to delete window.console when it is not overwritten, it will just pop up again. The fact that you are able to overwrite it in the first place (even in strict mode) without receiving any kind of warning (in my eyes) one of the key vulnerabilities of javascript (set setTimeout on nearly any page to 0 and see it tear itself apart), but as they say in spiderman:

With great power comes great responsibility

Update

To include a hint that this is specific to the implementation of the browser / engine and not any requirement of the language itself: In nodejs, deleting both engine-specified properties and ecma-script properties on the global object works:

delete this.console //=> true
console //=> ReferenceError

delete parseInt //=> true
parseInt //=> ReferenceError

The exact same thing happens in Firefox.

I'm assuming the following, based on observations of my own.

Variables are first checked to see if they match local variables, if not, then it will be checked to see if they match window.variable.

When you set console to 1, you set the local variable console to 1, so any lookups will see that instead of window.console (which still exists). When you delete console the local variable console gets deleted. Now any lookups of console will match window.console. That's why you get the behaviour you get.

I am assuming this based on experimenting with the JavaScript interpreter in Firefox. And, I'm sorry about incorrect terminology (feel free to edit), I'm not that experienced with namespaces.

The delete operator removes a property from an object.

...

You can use the delete operator to delete variables declared implicitly but not those declared with the var or the function statement.

See delete on MDN

Edit:

See also Understanding delete if you're really into hardcore JavaScript.

What happens is you are overwriting the objects prototype, then you delete the overwritten value and what is left... is the original object, which is it's prototype.

Expected behavior. Little known fact that the Javascript console does not run in the browser's global space, but rather it runs within its own anonymous function.

I know that different browsers handle things differently, but in short -- delete does not operate as expected because it isn't operating in the global space.

If you really want to see things break, try playing with delete window.console

Ok, it is official -- I'm an idiot. One of the new features in ECMAScript is the ability to declare a property as dontdelete. Sorry about that confusion.

发布评论

评论列表(0)

  1. 暂无评论