在对象内的函数之间传递值

时间:2015-10-18 05:59:19

标签: javascript function object

我正在制作迷你日历。我试图将适当的值传递到对象的视图部分。但我继续在视图部分中定义未定义。我究竟做错了什么?

var date = {  

  monthsArray: ["January", "February","March","April","May","June","July","August", "September", "October", "November","December" ],
  init: function() {
    var fullDate = new Date();
    this.dateParsed(fullDate);
    this.view();
  },
  stringifyMonth: function(monthNumber) {
    var monthName = this.monthsArray[monthNumber]
    return monthName
  },
  dateParsed: function(fullDate){
   var fullDate = new Date();
   var monthNumber = fullDate.getMonth();
   var dayNumber = fullDate.getDate();
   var calanderYear = fullDate.getFullYear();
   this.stringifyMonth(monthNumber)
   return calanderYear
  },
  view: function(monthName){

    console.log(this.stringifyMonth())   ///  undefined 


  }

}.init()

2 个答案:

答案 0 :(得分:3)

两件事:

  1. 将当前月份传递给view功能。您可以使用getMonth()
  2. 从日期对象中获取月份
  3. 将同一个月传递给stringifyMonth
  4. view

    查看突出显示的更改和评论

    var date = {
    
      monthsArray: ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"],
      init: function() {
        var fullDate = new Date();
        this.dateParsed(fullDate);
    
        
        // Get the current month from date object and pass to the view()
        this.view(fullDate.getMonth()); // <-----
      },
      stringifyMonth: function(monthNumber) {
        var monthName = this.monthsArray[monthNumber]
        return monthName
      },
      dateParsed: function(fullDate) {
        var fullDate = new Date();
        var monthNumber = fullDate.getMonth();
        var dayNumber = fullDate.getDate();
        var calanderYear = fullDate.getFullYear();
        this.stringifyMonth(monthNumber)
        return calanderYear
      },
      view: function(monthName) {
        
        // Pass the monthName to the stringifyMonth()
        console.log(this.stringifyMonth(monthName)); // <-----
      }
    }.init();

答案 1 :(得分:2)

stringifyMonth需要一个参数,但你没有传递一个参数。 因此, null 作为参数传递,然后您尝试访问this.monthsArray [null],这是未定义的。

尝试传递一个像1这样的参数,你会看到它打印二月。