-2

好的,请考虑以下几点:

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。为什么?

4

2 回答 2

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

您的错误在此代码中。您需要将sourceand传递scopegetRate函数。没有这些参数,$("Date", source).text()将一无所获,因此函数返回null,因为你告诉它。

if (!dateValue) {
  return null;
}

要修复它,您需要将代码更改为:

getAllRates: function(source, scope){
  return getRate(source, scope);  // getRate needs to be passed the parameters
}
于 2013-08-07T14:12:29.420 回答
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了使用。

于 2013-08-07T14:17:12.117 回答