在理解如何调用JavaScript对象中的值时遇到困难

在理解如何调用JavaScript对象中的值时遇到困难,javascript,knockout.js,momentjs,Javascript,Knockout.js,Momentjs,我使用knockout.js和moment.js来计算给定月份的一些值。以下代码按预期工作: var calendarViewModel = { selectedMonth: ko.observable(moment().format("M")), daysInMonth: ko.observable(moment().month(3).daysInMonth()) }; ko.applyBindings(calendarViewModel); 所选月份的返回值为“4”,所选

我使用knockout.js和moment.js来计算给定月份的一些值。以下代码按预期工作:

var calendarViewModel = {
    selectedMonth: ko.observable(moment().format("M")),
    daysInMonth: ko.observable(moment().month(3).daysInMonth())
};

ko.applyBindings(calendarViewModel);
所选月份的返回值为“4”,所选月份的返回值为“30”

但我想做的是根据selectedMonth的当前值(将发生变化)计算daysInMonth的值。我能想到的最好的代码是:

var calendarViewModel = {
    selectedMonth: ko.observable(moment().format("M")),
    daysInMonth: ko.observable(moment().month(calendarViewModel.selectedMonth() - 1).daysInMonth())
};

ko.applyBindings(calendarViewModel);
我得到未捕获的类型错误:无法在控制台中读取未定义的属性“selectedMonth”。 我很难理解的是如何在这种情况下正确引用selectedMonth。如果我在viewModel之外的其他通用变量中创建selectedMonth,我所做的一切都可以正常工作

我很确定这与我对JavaScript对象的(拙劣)理解有关,与库本身无关。

您需要为此创建一个:

var calendarViewModel = function(){
    var self = this;
    self.selectedMonth = ko.observable(moment().format("M"));
    self.daysInMonth = ko.computed(function(){
        var selectedMonth = self.selectedMonths();
        return moment().month(selectedMonth - 1).daysInMonth();
    });
};

ko.applyBindings(new calendarViewModel());
至于区别。。。在这里,我们正在创建一个
calendarViewModel
的实际实例,它将按照您期望的方式设置
上下文


它还使用闭包来确保您可以在
computed

中正确访问自己的成员。这完全符合预期,谢谢!如果您有时间快速跟进,我现在不知道如何将新值写入selectedMonth(self的b/c),尽管我可能只需要阅读其中一些内容。再次感谢@binaryorganic—通常您会让它通过数据绑定来处理,但是如果您想直接编写一个新值,您可以直接执行
self.selectedMonth(4)
或类似操作来编写它。您可以创建一个可以调用的方法,或者将视图模型的实例保存为局部变量以供以后使用。至于JavaScript,我强烈建议阅读Douglas Crockford的JavaScript:The Good Parts