2012-07-12 93 views
3

這是代碼:對象訪問不起作用

(function(Info, undefined) { 
    var createInfoTableForFeature = function (obj) { 
     var data2form = {}; 
     data2form.name = obj.name; 
     data2form.state = obj.state; 
     data2form.stateid=obj.stateId; 
     data2form.city = obj.city; 
     data2form.cityId=obj.cityId; 
     data2form.sector = obj.sector; 
     data2form.sectorId=obj.sectorId; 
     data2form.municipality = obj.municipality; 
     data2form.municipalityId=obj.municipalityId; 
     data2form.parish = obj.parish; 
     data2form.parishId = obj.parishId; 
     data2form.postcode = obj.postcode; 
    } 
    Info.copy2form = function(data){ 
     console.log(data); 
    } 
})(window.Info = window.Info || {}); 

當我打電話Info.copy2form(data2form)data2formundefined

+2

哪裏是信息.copy2form被調用? – Chandu 2012-07-12 21:19:08

+2

在哪裏調用'Info.copy2form(data2form)'? 'data2form'只存在於'createInfoTableForFeature'中。 – 2012-07-12 21:19:23

+0

您不應該使用'undefined'作爲參數名稱。 – EricG 2012-07-12 21:21:16

回答

5

你想data2form是全球性的,那麼你就必須刪除德var關鍵字變量data2form的聲明之前,使其全球。

如果你想讓它入店來自世界各地,但Info容器內,然後就可以像這樣把它聲明:

Info.data2form = {}; 

,然後調用你的函數是這樣的:

Info.copy2form(Info.data2form) 
3

您的文章似乎並不JSON到目前爲止相關的,很好哦。

您的data2form不存在函數外部。您應該將其分配給window.data2form或在函數外部定義var data2form。

1

這不起作用,因爲data2form是匿名函數(createInfoTableForFeature)中的局部變量。

這是1000級的解決方案之一:

function createInfoTableForFeature(obj) { 
    var data2form = {}; 
    data2form.name = obj.name; 

    data2form.state = obj.state; 
    data2form.stateid=obj.stateId; 

    data2form.city = obj.city; 
    data2form.cityId=obj.cityId; 

    data2form.sector = obj.sector; 
    data2form.sectorId=obj.sectorId; 

    data2form.municipality = obj.municipality; 
    data2form.municipalityId=obj.municipalityId; 

    data2form.parish = obj.parish; 
    data2form.parishId = obj.parishId; 

    data2form.postcode = obj.postcode; 

    return data2form; 
} 

var data2form = createInfoTableForFeature(obj); 
Info.copy2form(data2form); 
+0

我假設你打算把'return data2form;'添加到'createInfoTableForFeature'? – 2012-07-12 22:10:35

+0

你是對的!謝謝Rocket! – Besnik 2012-07-12 22:13:45