Javascript:从私有函数访问公共变量

时间:2014-05-14 08:42:00

标签: javascript oop

我正在学习javascript,正在尝试下面的一些代码。我将下面的javascript对象称为

var client=new atrmsClient('6247543');

var val=client.getRosterData();

我在这一行收到错误:

var postData= {"cmdShow": "Show", "txtEmpId" : EmpId, "txtPeopleSoft_Id": EmpId, "__VIEWSTATE":  viewState   }

EmpId未定义。谁能告诉我我做错了什么?

"use strict";

function atrmsClient(EmployeeId)
{
    this.EmpId=EmployeeId;

    var siteUrl="http://wncrpma011.japa.ad.aexp.com/TransportRoster/EmployeeReport.aspx";


    var getViewState=function()
    {

            $.ajax
        ({
            type: "GET",
            url: siteUrl,
            dataType: 'html',           
            processData: false,
                xhrFields: 
                {
                    withCredentials: true
                }
        })
        .done(ExtractViewState).fail(errorFunc).always(alwaysFunc);

        return "";

    };

    var SendPostRequest=function(viewState)
    {
        var postData= {"cmdShow": "Show", "txtEmpId" : EmpId, "txtPeopleSoft_Id": EmpId, "__VIEWSTATE":  viewState   }

            $.ajax
        ({
            type: "POST",
            url: siteUrl,
            data: postData,
            dataType: 'html',           
            processData: false,
                xhrFields: 
                {
                    withCredentials: true
                }
        })
        .done(parseRosterData).fail(errorFunc).always(alwaysFunc);


    };


    var parseRosterData=function(data)
    {
        console.log(data);



    };

    var ExtractViewState=function(data)
    {

        var rawResponse=data;
        var viewState=$(rawResponse).find('input[name=__VIEWSTATE]')[0].value;
        console.log(viewState);

        SendPostRequest(viewState);

    };

    var errorFunc=function()
    {


    };


    var alwaysFunc=function()
    {


    };

    this.getRosterData=function()
    {
        var viewStateVal=getViewState();
        console.log("calling");
        return "";
    };



}

2 个答案:

答案 0 :(得分:3)

您永远不会声明名为EmpId的变量。

您拥有的唯一EmpIdatrmsClient个实例的属性

添加

var EmpId = EmployeeId;

...或者只使用EmployeeId,因为它仍在范围内。

答案 1 :(得分:1)

另一种解决方案可能是:

function atrmsClient(EmployeeId) {

    var that = this;
    this.EmpId=EmployeeId;

    var SendPostRequest=function(viewState) {
        var postData= {"cmdShow": "Show", "txtEmpId" : that.EmpId, "txtPeopleSoft_Id": that.EmpId, "__VIEWSTATE":  viewState   }
        // ...
    };

}

这取决于您是否需要EmpId来自外部,即使用client.EmpId。如果是,那么此解决方案应该适合您的需求。否则,请使用@ Quentin。