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

4

3 回答 3

5

您想data2form成为全局的,那么您必须var在变量声明之前删除 de 关键字data2form以使其成为全局变量。

如果你想让它可以从任何地方访问,但在Info容器内,那么你可以这样声明它:

Info.data2form = {};

然后像这样调用你的函数:

Info.copy2form(Info.data2form)
于 2012-07-12T21:40:14.593 回答
3

到目前为止,您的帖子似乎与 JSON 无关,哦。

您的 data2form 在函数之外不存在。您应该将其分配给 window.data2form 或在函数外部定义 var data2form。

于 2012-07-12T21:19:44.093 回答
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);
于 2012-07-12T21:24:06.030 回答