关于javascript:TypeScript var scoping

TypeScript var scoping

所以我最近开始使用typescript,到目前为止我很享受它,但是有一个问题,我就是不明白它为什么不能正常工作。

"var"关键字在typescript中仍然可以自然访问,我知道它是一个函数范围,而不是"let"关键字的块范围。我有以下代码,但我不明白它为什么不能工作:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
 class Calendar {
      month: number;
      months: string[];
      weekday: number;
      day: number;
      constructor() {
        this.month = date.getMonth();
        this.months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'November', 'December'];
        this.weekday = date.getDay();
        this.day = date.getDate();
      }
      nextMonth() {
        var months = this.months;
        var currentmonth: number = this.month;

        el('.icono-caretRight').addEventListener('click', () => {
          currentmonth = (currentmonth + 1) % months.length;
        }, false);

        month = currentmonth;
        return month;
      }
      previousMonth() {
        el('.icono-caretLeft').addEventListener('click', () => {
          month--;
        }, false);
      }
    }

let calendar = new Calendar();
let month = calendar.month;
let nextmonth = calendar.nextMonth();
console.log(nextmonth);

查看nextmonth()函数。我不知道为什么"month"变量没有递增。我到底做错了什么?

注意:我使用的是jspm+typescript(插件类型脚本)。

事先谢谢!


the"var" keyword is still accessible in TypeScript naturally and I know that it's a function scope, versus block scope for the"let" keyword. I have the following code and I can't figure out why it's not working:

你对scoping的理解是正确的。

以下代码确实有效:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class Calendar {
      month: number = 0;
      months: string[];

      constructor() {
        this.months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'November', 'December'];
      }
      nextMonth() {
        var months = this.months;
        var currentmonth: number = this.month;
        currentmonth = (currentmonth + 1) % months.length;
        month = currentmonth;
        return month;
      }
    }

let calendar = new Calendar();
let month = calendar.month; // 0
let nextmonth = calendar.nextMonth();
console.log(nextmonth); // 1

我怀疑你对monthvs.this.month和/或addEventListenervs.实际调用函数感到困惑。

更多

根据用户意见:

I understand that the this.month is 0 since well the date.getMonth() is actually 0. My problem in that is doesn't want to increment, probably I don't get the addEventListener part of the function or maybe like you said I'm confused, because it's suppose to increment on click correct? It has to return a new value everytime the user clicks right? Or... Not sure anymore though

代码

1
2
3
el('.icono-caretRight').addEventListener('click', () => {
          currentmonth = (currentmonth + 1) % months.length;
        }, false);

可能是您要在构造函数中执行的操作。很可能你想要:

1
2
3
el('.icono-caretRight').addEventListener('click', () => {
   this.nextMonth();
}, false);