Let’s say we have this code (forget about prototypes for a moment):
function A(){
var foo = 1;
this.method = function(){
return foo;
}
}
var a = new A();
is the inner function recompiled each time the function A is run? Or is it better (and why) to do it like this:
function method = function(){ return this.foo; }
function A(){
this.foo = 1;
this.method = method;
}
var a = new A();
Or are the javascript engines smart enough not to create a new ‘method’ function every time? Specifically Google’s v8 and node.js.
Also, any general recommendations on when to use which technique are welcome. In my specific example, it really suits me to use the first example, but I know thath the outer function will be instantiated many times.
From what I understand, it is not so much a matter of “compiling” the function as it is having a different “scope” each time it is executed.
The second method you used will always have
methodfrom the same scope.The first method puts
methodinside the scope of theA()function call. So any information that is inside that scope (var foo, function parameters, etc) are stored in that instance of the functions scope. So, the same function code will be referenced each time, but it will be in a different scope (and therefore a different “object”).