Return Chrome Dev tools function

This question can be answered elsewhere, but I was not even sure how to start the search for the answer. I am new to JavaScript, so this is a fight for me to understand.

Given the following code:

function multiple(n) { function f(x) { return x * n; } return f; } var triple = multiple(3); var quadruple = multiple(4); 

When I pass the following to the console:

 console.log(triple(5)); 

I get what I expect, that is 15. Similarly, with any number, it will be tripled (or quadrupled if I use the second function).

But when I enter the triple into the console, I get the following code:

 f(x) { return x * n; } 

Do not return the console ...

 f(x) { return x * 3; } 

... since 3 is encoded into a function by virtue of the following code:

 var triple = multiple(3); 
+6
source share
3 answers

3 not hard-coded in function. The code f refers to the variable n , not to the number 3 . It happens in your code that there is no way to change n , but imagine some code where there is a way to change n :

 function multiple(n) { function f(x) { return x * n; } function modifyN(newN) { n = newN; } return { f: f, modifyN: modifyN }; } var resultFor3 = multiple(3); var triple = resultFor3.f; var modifyTripleN = resultFor3.modifyN; 

As you can see, n not hardcoded; it is no different from any other variable. In your specific example, there is no way to change n after multiple completes, but that does not make the values ​​inside the closure created by calling multiple any way "hard-coded."

+3
source

Well, this is the same as yours:

  var n = 3; function f(x) { return n * x; } 

If you register f , you will see the function above, but when it is called, n will get its value from the nearest variable n in the scope chain, in our case n = 3 value for n declared in the global scope.

I don’t know how the JS engine stores the variable n inside this closure (in your case, the closure created by the multiple function), but what’s important is that the variables inside the closure are not stored by reference by value.

+2
source

Entering triple simply shows the source code of your function.

since 3 is encoded into a function by virtue of the following code

This is a false statement. You do not change the source code of the function. To change the source code, you have to redefine the whole function. All you do is pass a parameter. The console gives you the right exit.

When you pass a parameter to a function, at a high level, at run time, it only looks for the value to be stored at the memory address for that variable (or something like that). But he does not rewrite the source code of the function.

+2
source

All Articles