首页 > typescript中如何new一个时间

typescript中如何new一个时间

在js中一般获取时间的写法是 date = new Date()
如果this上下文不在window中则加上 date = new window.Date()
现在typescript中遇到的情况是如下

class Main{
    constructor(){
    Main.test()
    }
    static test(){
        var Date = new Date()
    }
  
}

编译后,运行在浏览器,Date会报错
如下

因为此时this指向function test,所以必须加上window,在js中可以new window.Date(),但是typescript 中new一个window.date编译无法通过

请问这种情况下改如何解决,感激不尽?


  1. typescript是javascript的超集,所以你在js中如何做就在ts中如何做。

  2. js语言也有关键字,关键字不能用做变量名。

  3. Date是内置类,无论你在哪里调用,都不会受this关键字的影响。

  4. 一楼是正解,Date被重写了。


问题不在于Date是否能new,而在于你重置了Date这个变量,把代码改一改:

class Main{
    constructor(){
    Main.test()
    }
    static test(){
        var time = new Date()
    }
  
}

这下子,再试试看?

【热门文章】
【热门文章】