简体   繁体   中英

JavaScript delete objects behaves differently in different browsers

I was searching for a suitable explanation for this on SO, but couldn't find the one which answers my question.

I read that in JavaScript, Objects couldn't be deleted. So to find out, I was playing around in my browser's console. I created an object like this:

var a = {x:10};

Then I did delete ax which returned true .(No surprises here)

Then went on to delete the object like this: delete a .

But what stumped me was while Google Chrome returned false , Firefox returned true

How is it possible that an Object is "deleted" in one browser and not in another? Is there something I am missing here or Is it browser implementation that causes this?

In FF v27: Firefox控制台

In Google Chrome v33 Google Chrome浏览器控制台 .

This is due to differences in the internal method of running console code in Firefox and Chrome.

In Firebug, console code is evaluated using a form of eval for extension code . However, in Chrome the code in the console is evaluated using internal methods 1 which simulate actual code running, not directly using JavaScript's eval function.

The [[Configurable]] internal property descriptor attribute determines whether an attempt to delete the variable/property will succeed. If it's false, it will not delete the property and the delete operator will return false.

Any variables defined in eval code have [[Configurable]] set to true . However, if you define a variable outside code passed to eval , that attribute will be set to false .

This difference in behaviour between eval and other types of executable code is specified in the ECMAScript standard under section 10.5:

2. If code is eval code, then let configurableBindings be true else let configurableBindings be false .

1: This code is only the frontend code, not the actual internals, which goes down many levels.

I found this : it seems is a Firebug issue: When you use the built-in developer tool in Chrome, it is directly using the JS engine. Firebug is a plugin created in JS, so the only way to execute something is using "eval", which seems it's not adding the "don't delete" property to the object.

delete removes objects, but not variables.

I'll add some point to @Qantas's answer:

According to MDN delete operator reference :

Returns Throws in strict mode if the property is an own non-configurable property (returns false in non-strict). Returns true in all other cases.

That means, a non-configurable variable cannot be deleted through a delete operator. However, if a variable is configurable, as in @Qantas's answer, is defined in a eval() , then it can be deleted using the delete operator.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM