简体   繁体   中英

What is really happening when I call a function?

This might be a simple question but I've been thinking lately. I've tried researching for the answer but I have yet to find a satisfactory one.
Basically, what's happening behind the scene when I call a function? Say:-

function sayHello(){
    console.log('hello');
}
sayHello(); //what's happening here?

I know that doing sayHello.call(); or sayHello.apply(); is the same thing as doing sayHello(); but is there any more information on what's happening underneath or is it behind the mysterious native code?

Here are some of the things the interpreter does to make a JS function call:

  • A new scope object is created. An arguments object is created and put into the scope object with any arguments passed to the function in it.
  • Any local variables in the new function are put into the scope object.
  • A reference to the next line of code is pushed onto the execution stack (so the interpreter knows where to go when the function returns).
  • The this pointer is set as appropriate.
  • Execution is transferred to the code of the function.

This is managed by the internals of the JS interpreter (one of its many jobs) which is likely native code.


If you want to call function B() anytime function A() is called, you can replace function A() with your own proxy which calls function B() and then calls the original A() .

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