如何从javascript中的嵌套函数中检索var?

时间:2013-08-07 13:48:32

标签: javascript

好的,请考虑以下事项:

function(){
  function getRate(source, scope) {
    var dateValue = $("Date", source).text() || "";
    if (!dateValue) {
      return null;
    }
    var d = new Date();
    var dailyPrice = $("DailyPrice", source).text() || "";
    var weeklyPrice = $("WeeklyPrice", source).text() || "";
    var monthlyPrice = $("MonthlyPrice", source).text() || "";
    var isAvailable = $("IsAvailable", source).text() === "1";
    var minimumStay = Number($("MinimumStay", source).text());

    return {
      date: new Date(dateValue),
      dailyPrice: dailyPrice,
      weeklyPrice: weeklyPrice,
      monthlyPrice: monthlyPrice,
      reserved: !isAvailable,
      minimumStay: minimumStay
    };
  }

  return {
    getRates: function(xml){
      return getRates(xml);
    },
    getAllRates: function(source, scope){
      return new getRate();
    },
  };
}

如何从此函数外部获取dailyPrice我尝试了以下内容但它返回null

var getitall = getAllRates();

当我通过调试器运行它时,它会进入函数,但总是将值返回为null。 为什么?

2 个答案:

答案 0 :(得分:1)

getAllRates: function(source, scope){
  return new getRate();
}

您的错误在此代码中。您需要将sourcescope传递给getRate函数。如果没有这些参数,$("Date", source).text()将找不到任何内容,因此函数会返回null,因为您告诉它。

if (!dateValue) {
  return null;
}

要解决此问题,您需要将代码更改为:

getAllRates: function(source, scope){
  return getRate(source, scope);  // getRate needs to be passed the parameters
}

答案 1 :(得分:1)

很难说出你究竟想要完成什么。但是,试试这个:

http://jsfiddle.net/SmwNP/4/

var FooBar = (function() {
    function getRate(source, scope) {
        var dateValue = $("Date", source).text() || "";
        if (!dateValue) { return null; }
        var d = new Date();
        var dailyPrice = $("DailyPrice", source).text() || "";
        var weeklyPrice = $("WeeklyPrice", source).text() || "";
        var monthlyPrice = $("MonthlyPrice", source).text() || "";
        var isAvailable = $("IsAvailable", source).text() === "1";
        var minimumStay = Number($("MinimumStay", source).text());
        return {
            date: new Date(dateValue),
            dailyPrice: dailyPrice,
            weeklyPrice: weeklyPrice,
            monthlyPrice: monthlyPrice,
            reserved: !isAvailable,
            minimumStay: minimumStay
        };
    }
    return {
        getRates: function(xml) {
            console.log('executing getRates');
            //return getRates(xml);//where is there a getRates() function?
        },
        getAllRates: function(source, scope){
            console.log('executing getAllRates');
            return getRate(source, scope);
        }
    };
});

var something = FooBar();
something.getRates('z');
something.getAllRates('x', 'y');

至少,这会使getAllRates暴露出来。