函数中的对象访问不起作用

时间:2012-07-12 21:14:51

标签: javascript scope

这是代码:

(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

3 个答案:

答案 0 :(得分:5)

您希望data2form是全局的,然后您必须在声明变量var之前删除de data2form关键字,以使其成为全局。

如果您希望从Info容器内的任何地方访问它,那么您可以这样声明:

Info.data2form = {};

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

Info.copy2form(Info.data2form)

答案 1 :(得分:3)

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

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

答案 2 :(得分: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);