0

So say I have a function like this:

function cookie(){
    var a = 5; 
    function cat(){return a}
    return cat()}

cookie() // 5

It works fine, it gets the variable a from the parent function. Now, when I define the cat function outside of cookie, it doesn't work like that

function cat(){return a}
function cookie(){
    var a = 5; 
    return cat()}

cookie() // "a is not defined" error message

So this does make sense, but I'm still wondering how I could pass the local variable from the function cookie, to the function cat.

How do I go about making the local variable "a" from cookie to also be defined in cat, as a local variable?

2 Answers2

2

You can't. Variables are trapped in whatever scope you declare them in.

You can pass the value of the variable as a function argument just like any other.

function cat(passed_a) {
  return passed_a;
}

function cookie() {
  var a = 5;
  return cat(a);
}

cookie();
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
1

I'm guessing you mean pass a as an argument into cat:

function cat(somevar){
    return somevar
} 
function cookie(){
    var a = 5; 
    return cat(a)
}

cookie()

What this does is declare cat function and takes an argument. Inside cat, the argument is returned. Now you can just pass a into the function and return it in cookie.

Andrew Li
  • 55,805
  • 14
  • 125
  • 143
  • @CaptainCrunch I mean, you could hack something up, but I wouldn't recommend it. – Andrew Li Sep 21 '16 at 21:53
  • Thanks for the answer! I figured you might need to do something like this, but is there any way to bind a to cat through cookie, without editing cat? – Captain Crunch Sep 21 '16 at 21:54
  • Alrighty, I'll just stick with what you did. – Captain Crunch Sep 21 '16 at 21:54
  • You could of course get rid of `somevar`, just implicitly pass `a` and return `arguments[0]`. That will still modify `cat` though. – Andrew Li Sep 21 '16 at 21:56
  • 1
    @CaptainCrunch well, you could do `function cat() { return this.a }` and then provide the value of `this` using something like `cat.call({a: 5})`. In this case, it's a bit roundabout and it's easier to pass an agument. – VLAZ Sep 21 '16 at 21:57
  • @vlaz agreed, but I believe the OP wants to return a without modifying cat which isn't possible – Andrew Li Sep 21 '16 at 21:59
  • 1
    I understand that, however, there isn't another way of changing the context of a function - if `cat` doesn't have access to the variable, then it simply won't use it. – VLAZ Sep 21 '16 at 22:01