Javascript delete a function

前端 未结 3 935
迷失自我
迷失自我 2020-12-14 07:51

How can I delete a function

i.e

test=true;
delete test;
=> true

function test() {..}

delete test()
=> false

Delete usually

相关标签:
3条回答
  • 2020-12-14 08:18

    delete only works for properties of objects. If test() was inside an object, you could delete it, but if it's a stand alone function, you're stuck with it, unless you nullify it or define it as something else.

    Object Delete

    var obj = {
        test: function() {
            console.log("I'm a test");
        }
    }
    
    obj.test(); //I'm a test
    delete obj.test;
    obj.test(); //Nothin'
    

    Function Reassign

    function test() {
        console.log("I'm a test");
    }
    
    test(); // I'm a test
    
    delete test;
    
    test = undefined;
    
    test(); // TypeError
    
    0 讨论(0)
  • 2020-12-14 08:26

    No, you can not delete the result of a function declaration.

    This is a part of the language specification.

    If you check out the description of the delete operator in JavaScript:

    If desc.[[Configurable]] is true, then

    • Remove the own property with name P from O.

    • Return true.

    If you go to the browser and run the following in the console:

    >function f(){}
    >Object.getOwnPropertyDescriptor(window,"f")
    

    You would get:

    Object {value: function, writable: true, enumerable: true, configurable: false}

    What can be done:

    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.

    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
    

    Some more notes on delete

    • When your modern browser sees a delete statement, that forces it to fall to hash map mode on objects, so delete can be very slow (perf).

    • 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 :)

    0 讨论(0)
  • 2020-12-14 08:28

    You could always do:

    var testFunc = func() 
    {
        // stuff here
    }
    
    //...
    testFunc();
    //...
    
    testFunc = undefined;
    

    delete in JavaScript has no bearing on freeing memory, see here

    0 讨论(0)
提交回复
热议问题