JavaScript typeof function passed as argument returns undefined

The example below works fine, however I am trying to make the handleArcs() function more universal (i.e. handleLayer() ).

My layerVar has an onEachFeature property, which applies the onEachArc method to each layer function. I want handleArcs() take the onEachArc() function as an argument, but it does not work, and when I pass it and check with typeof , the result is undefined . This is basically a simple passing function as an argument to another function, but in this case it does not work.

My first guess was that something was wrong with this context. But since typeof thisShouldBeAFunction returns undefined back, I'm not sure what the problem is.

Any guesses what might be causing the problem?

 function onEachArc(feature, layer) { if (feature.properties) { layer.bindPopup("<b>" + feature.properties.linkstr + "</b> has speed " + feature.properties.speed + "."); } }; function handleArcs(data, layerVar, layerName, thisShouldBeAFunction) { alert(typeof thisShouldBeAFunction); //Add the feature to the map layerVar = new L.geoJson(data, { onEachFeature: onEachArc }).addTo(map); } getData('Layers/arcs.json').done(handleArcs(arcs, "Arcs", onEachArc)); 

getData() calls the jQuery AJAX method to get data from the server:

  function getData(url) { return $.ajax({ url : url, type: 'GET', error : function (xhr,status,error){alert("An error happened while loading a file: "+error+".")} }); } 
+5
source share
1 answer

As @Tushar said, do not immediately call handleArcs , wrap it in an anonymous function with the correct signature, and pass it to done .

 getData('Layers/arcs.json').done(function(data) { handleArcs(data, arcs, "Arcs", onEachArc); }); 

I do not quite understand the meaning

 layerVar = new L.geoJson(... 

inside handleArcs . You don't expect this job to affect the arcs variable you pass in, right?

About the global variable as a parameter:

 var aGlobal = "Test_One"; function TryToChangeIt(aParam) { aParam = "Test_Two"; } function MyFunction(aParam) { alert("Before: " + aGlobal); TryToChangeIt(aGlobal); alert("After: " + aGlobal); } 

By calling TryToChangeIt(aGlobal); , we pass the value - not the name - of the global variable. A new temporary variable is created by the javascript engine for use as a parameter, and aGlobal is assigned to it before calling TryToChangeIt . Inside TryToChangeIt we can change the value of this temporary variable, but this will not affect the value of aGlobal .

+2
source

Source: https://habr.com/ru/post/1232829/


All Articles