Reputation: 671
If i have a closure like the code below, how I can get the 'a' parameter outside the closure. JS engine use scope chain to get to find the value of 'a' when I call the closure, but is there some chance to get the 'a' value from global context?
function fn(a){
return function f(b){
console.log(a + " " + b);
}
}
BR, Igor
Upvotes: 0
Views: 30
Reputation: 1
var count=0;
function add(){
return count+=1;
}
function sub(){
return count-=1;
}
function increment(){
document.getElementById("element").innerHTML=add();
}
function decrement(){
document.getElementById("element").innerHTML=sub();
}
<button type="button" onclick="increment()">Increment!!</button>
<button type="button" onclick="decrement()">Decrement!!</button><br><br><br>
<div id="element"><div>
Upvotes: 0
Reputation: 138257
Some trick would be assigning it to the function object:
function fn(a){
function f(b){
console.log(a + " " + b);
}
f.a = a;
return f;
}
So you can do:
const result = fn(2);
console.log(result.a, result(2));
However a closure is there to encapsulate things. If you don't want that, you should not use a closure.
Upvotes: 1