简体   繁体   中英

javascript function rewrite itself inside function how does it work behind the scene?

this is some code i have already tried

function myFunc(){

    alert("3");

    myFunc = function (){

        alert("something else");

    }


}

i want to understand what happens behind the scene in javascript

when i execute myFunc its alert 2 and second when i execute it alerts "something else" . what is happening behind the scene when this myFunc is called how does function rewrites itself from within the function ?

myFunc is in the global namespace, so you can redefine it, which happens when you assign a new function to it with myFunc = function() ... .

Functions are objects, and as such can be assigned new definitions over time. You could even set myFunc = undefined; if you wanted to prevent the function from running again.

You're simply redeclaring the function the second time.

On page load, you declare myFunc() which alerts 3.
When you execute myFunc() , you declare a new function which alerts "something else";

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