Javascript删除功能 [英] Javascript delete a function
问题描述
如何删除功能
即
test=true;
delete test;
=> true
function test() {..}
delete test()
=> false
删除通常适用于变量,但不适用于函数.
Delete usually works for variables but it doesn't work for functions.
推荐答案
不,您不能删除
语言规范的一部分.
如果您在JavaScript中签出了删除运算符的说明:
If you check out the description of the delete operator in JavaScript:
如果描述[[Configurable]]为真,则
If desc.[[Configurable]] is true, then
-
从O删除名称为P的自有财产.
Remove the own property with name P from O.
返回true.
如果转到浏览器并在控制台中运行以下命令:
If you go to the browser and run the following in the console:
>function f(){}
>Object.getOwnPropertyDescriptor(window,"f")
您会得到:
对象{值:函数,可写:true,可枚举:true,可配置:false}
但是,您可以将结果分配给不是函数的另一个值,假设这是您对该函数的最后一个引用,则会发生垃圾回收并将其取消分配.
You can however, assign the result to another value that is not a function, assuming that is your last reference to that function, garbage collection will occur and it will get de-allocated.
出于除 getOwnPropertyNames
hasOwnProperty
之类的所有目的,诸如 f = undefined
之类的东西应该可以工作.在这种情况下,您可以改用functionExpression并将其分配给变量.但是,出于诸如 hasOwnProperty
之类的目的,它将失败,请在控制台中尝试!
For all purposes other than getOwnPropertyNames
hasOwnProperty
and such, something like f = undefined
should work. For those cases, you can use a functionExpression instead and assign that to a variable instead. However, for those purposes like hasOwnProperty
it will fail, try it in the console!
function f(){}
f = undefined;
window.hasOwnProperty("f");//true
关于删除的更多说明
-
当您的现代浏览器看到
delete
语句时,速度非常慢(perf).Some more notes on delete
When your modern browser sees a
delete
statement, that forces it to fall to hash map mode on objects, sodelete
can be very slow (perf).在带有垃圾收集器的托管语言中,使用
delete
可能会出现问题.您不必处理内存,语言会为您完成.In a managed language with a garbage collector, using
delete
might prove problematic. You don't have to handle your memory, the language does that for you.在您确实要使用诸如地图之类的对象的情况下,这是一个有效的用例,并且
In the case you do want to use objects like a map, that's a valid use case and it's on the way :)
这篇关于Javascript删除功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!