0

I'm new to JS. I try the function closure, just as in the documentation example and I get an uncaught reference. Why?

function fetchData(filter) {
    return $.ajax({
        type: "GET",
        contentType : "application/json; charset=utf-8",
        dataType: "json",
        url: "my_url"+route,
        data: filter
      });
};

function fetchDataSource(filter) {
  var route = "data_source";
  return fetchData(filter);
};

And now, when I call the function:

var filter;
fetchData(filter);

I have the following error:

Uncaught ReferenceError: route is not defined at fetchData (:6:49) at fetchDataSource (:3:10) at :1:1

Why is route not visible in my function?

Thanks

Carmellose
  • 4,815
  • 10
  • 38
  • 56

1 Answers1

1

the fetchData function does not include route in its closure because route is defined inside a sibling function. There are ways to make it closure around route as you would expect, somethign like this would work:

var route;

function fetchData(filter) {
    return $.ajax({
        type: "GET",
        contentType : "application/json; charset=utf-8",
        dataType: "json",
        url: "my_url"+route,
        data: filter
      });
};

function fetchDataSource(filter) {
  route = "data_source";
  return fetchData(filter);
};

Because route is defined in the scope that contains fetchData here, whereas it's not in yours.

TKoL
  • 13,158
  • 3
  • 39
  • 73