簡體   English   中英

作為參數傳遞的JavaScript typeof函數返回undefined

[英]JavaScript typeof function passed as an argument returns undefined

下面的例子工作正常,但是,我試圖使函數handleArcs()更通用(即handleLayer() )。

我的layerVar有一個屬性onEachFeature ,它將onEachArc上的方法應用於onEachArc的每個特征。 我希望handleArcs()將函數onEachArc()作為參數,但它不起作用,當我傳遞它並檢查typeof ,結果是undefined 基本上,將一個函數作為參數傳遞給另一個函數很簡單,但在這種情況下它不起作用。

我的第一個假設是這個背景出了this 但是因為typeof thisShouldBeAFunction返回undefined我現在不確定問題是什么。

有沒有猜到可能導致問題的原因?

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()調用jQuery AJAX方法從服務器獲取數據:

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

正如@Tushar所說,不要立即調用handleArcs ,將其包裝在具有適當簽名的匿名函數中並將其傳遞給done

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

我不太明白這一點

layerVar = new L.geoJson(...

里面的handleArcs 你不希望這個賦值影響你傳入的arcs變量,對嗎?

關於全局變量作為參數:

var aGlobal = "Test_One";

function TryToChangeIt(aParam) {
  aParam = "Test_Two";
}

function MyFunction(aParam) { 
  alert("Before: " + aGlobal);

  TryToChangeIt(aGlobal);

  alert("After: " + aGlobal);
}

通過調用TryToChangeIt(aGlobal); 我們傳遞的是全局變量的值 - 而不是名稱 javascript引擎創建一個新的臨時變量作為參數,並在調用TryToChangeIt之前TryToChangeIt分配aGlobal的值。 TryToChangeIt內部,我們可以更改此臨時變量的值,但這不會影響aGlobal的值。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM