在新日期调用getTime时,未定义不是函数 [英] Undefined is not a function when calling getTime on new Date

查看:296
本文介绍了在新日期调用getTime时,未定义不是函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

尝试运行时,我得到未定义不是函数。我缺少什么?

I get "undefined is not a function" when trying to run this. What am I missing?

function bench(func) {
  var start = new Date.getTime();

  for(var i = 0; i < 10000; i++) {
    func();
  }

  console.log(func, new Date.getTime() - start);
}

function forLoop() {

    var counter = 0;
    for(var i = 0; i < 10; i++) {
      counter += 1;
    }

    return counter;

}

bench(forLoop);


推荐答案

您需要使用:

new Date().getTime();

而不是

new Date.getTime();






以下是对正在进行的操作的一些解释。当你这样做:


Here's some explanation of what was doing on. When you do:

new Date.getTime();

它查找 getTime()属性在 Date 构造函数上,那是 undefined ,因为该属性存在于原型或实际实例化对象上,而不是构造函数上本身。然后它试图做新的未定义的这显然不起作用并且给你看到的错误。

it looks for the getTime() property on the Date constructor and that is undefined because that property exists on the prototype or actual instantiated objects, not on the constructor itself. Then it tries to do new undefined which obviously doesn't work and gives you the error you saw.

当你这样做:

new Date().getTime();

它基本上是这样做的:

(new Date()).getTime();

因为运营商优先权,这就是你想要的。它将创建一个新的 Date()对象,然后在其上调用 .getTime()方法。

because of operator precedence and that is what you want. It will create a new Date() object and then call the .getTime() method on it.

这篇关于在新日期调用getTime时,未定义不是函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆