Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how many copies of the inner function will be created

These days most of my work is related to js developing.

However I suddenly found that I am confused with some questions.

Check this code(I add one method to a custom class):

MyCustomClass.prototype.fun=function(xx){
  this.options={.....}
  function innerFun01(){}
  function innerFun02(){}
}

Now,use it.

var mcc=new MyCustomClass();
mcc.fun(xxxx);

var mcc2=new MyCustomClass();
mcc2.fun(xxxx);

Now,I wonder how many copies of the function "innerFun01" and "innerFun02" will be created in the memory?

I am really confused.

like image 498
hguser Avatar asked Aug 29 '11 14:08

hguser


1 Answers

Those functions will be constructed each time the function "fun" is called. (I suppose it's more correct to say that new instances of those functions will be constructed.)

It's OK. Modern JavaScript runtime systems are pretty good. It's possible that the translation of the source code into ... well whatever (thunks, machine code, threaded code, ...) is done when the outer function is first parsed, so that the actual "instantiation" of the functions is really cheap.

Lots of functional languages have similar characteristics. A local Scheme function declared with a (let ...) or something would similarly be brought into being each time its containing function is called.

like image 129
Pointy Avatar answered Sep 21 '22 17:09

Pointy