将javascript/Type脚本的2个功能合二为一

Bha*_*rat 0 javascript typescript angular

我有一个Date变量,我每秒更新它以使其生效.

现在这是我的变量.

var stationdate = new Date(data.localTime);
Run Code Online (Sandbox Code Playgroud)

我的Javascript代码每秒更新一次.

window.setInterval(function () {        
    stationdate = new Date(stationdate.setSeconds(stationdate.getSeconds() + 1));            
  }, 1000);
Run Code Online (Sandbox Code Playgroud)

和我的类型脚本代码将其返回到Angular UI.

window.setInterval(() => this.time = stationdate, 1000);
Run Code Online (Sandbox Code Playgroud)

我的问题.

如果两个函数都是分离的,它可以完美地工作.

但是如果我将它们组合起来就会停止工作

见下文.

window.setInterval(function () {        
    stationdate = new Date(stationdate.setSeconds(stationdate.getSeconds() + 1));
    this.time = stationdate;            
  }, 1000);
Run Code Online (Sandbox Code Playgroud)

AM I I I WITH WITH FAT FAT FAT FAT FAT FAT FAT FAT FAT FAT?

什么应该是正确的功能?

Sur*_*yan 5

每个人function都有自己的this背景.所以你this引用了函数表达式中的另一个对象.随着arrow function它指的是this包含它的外部arrow function.

使用箭头语法,没有必要使用window后面的前缀setInterval.

setInterval(() => {        
    stationdate = new Date(stationdate.setSeconds(stationdate.getSeconds() + 1));
    this.time = stationdate;            
  }, 1000);
Run Code Online (Sandbox Code Playgroud)

有关更多阅读箭头函数与函数声明/表达式 - 这是Javascript中的主要概念之一.