【问题标题】:Return objects from nested functions?从嵌套函数返回对象?
【发布时间】:2013-08-04 13:02:19
【问题描述】:

我正在尝试将函数内部的对象作为另一个函数内部的对象返回:

    function () {
    // body...
var dailyPrice = null; 
                function fun1(xml) {
                /***function**/
                }

                function fun2(xml) {
                /*function***/
                }
                function getRate(source, $scope) {
                    var dateValue = $("Date", source).text() || "";
                    if (!dateValue) {
                        return null;
                    }
                    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());
                    if (isNaN(minimumStay)) {
                        minimumStay = DEFAULT_MINIMUM_STAY;
                    }

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

                }
               return {
                    getallrates: function(source, $scope){
                        getRate(source, $scope);
                        console.log(getRate.dailyPrice);
                    },
                    init: function(xml) {
                        parseXml(xml);
                    },
                }
}

现在当我运行 getallrates();它返回未定义的为什么? 我也尝试过以下回报:

getallrates: function(source, $scope){
                    var allrates =  getRate();
                    var getdailyprice = allrates.dailyPrice;
                    console.log(getdailyprice);
                },

【问题讨论】:

  • 看起来您在return getRate(source, $scope) 上缺少return

标签: javascript function object angularjs


【解决方案1】:

把代码改成这样:

return {
                    getallrates: function(source, $scope){
                        return getRate(source, $scope);                            
                    },
                    init: function(xml) {
                        parseXml(xml);
                    },
                }

【讨论】:

  • 好的,我如何从这个父函数获取每日价格??
  • 你从 getRate 函数返回它,所以它应该像调用一样简单:var rates = getAllRates(source, $scope); console.log(rates.dailyPrice);
  • 这仍然没有返回我认为这是因为我正试图从 angularJS 的模块控制器中的服务中检索它,这让我很难过。
  • 把它从 Angular 中取出,放到一个单独的纯 JS 文件中,然后尝试一下,如果可以,那就是 Angular 问题
猜你喜欢
  • 2019-01-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-11-11
  • 1970-01-01
  • 2015-07-20
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多