根据 this MDN page , delete
关键字
Returns false only if the property exists and cannot be deleted. It returns true in all other cases.
但是,我看到 delete
返回 true
的情况,尽管属性没有被删除:
delete Window
delete alert
delete dir
delete console
delete 2
delete null
delete {}.x
...
事实上,window
的几乎所有属性都在 delete
时返回 true,正如在 about:blank
中运行以下脚本所见>:
for(a in window) { if(delete window[a]) { console.log(a); } }
但是,window
的大多数属性实际上并没有被删除。 delete
返回值的真正含义是什么?为什么它为未删除的属性返回 true
?
(注意:我会对解释 delete
行为的 Chromium 代码的引用感兴趣。)
最佳答案
窗口是一个host object ,其语义由宿主环境定义的,例如浏览器。 delete
应用于宿主对象的属性时比应用于 native 对象时更复杂。
Host objects may support these internal properties with any implementation-dependent behaviour as long as it is consistent with the specific host object restrictions stated in this document.
Section 11.4.1 - The delete
operator说
If IsUnresolvableReference(ref) then,
If IsStrictReference(ref) is true, throw a SyntaxError exception.
Else, return true.
因此当宿主对象不支持删除或修改属性时,它会返回一个无法解析的引用或一个假装被删除的引用。这两种方法都会导致 true
在非严格模式下返回。
关于javascript - 返回值 `delete` 的真正含义是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12145901/