Javascript删除功能 [英] Javascript delete a function

查看:43
本文介绍了Javascript删除功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何删除功能

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

关于删除的更多说明

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆