最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Undefined is not a function when calling getTime on new Date - Stack Overflow

programmeradmin1浏览0评论

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);

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);
Share Improve this question edited May 5, 2014 at 21:18 cookie monster 11k4 gold badges33 silver badges45 bronze badges asked May 5, 2014 at 20:44 meadowstreammeadowstream 4,1512 gold badges22 silver badges24 bronze badges 3
  • On which line do you get that error? – jfriend00 Commented May 5, 2014 at 20:46
  • 1 possible duplicate of javascript Date().getTime() is not a function – isherwood Commented May 5, 2014 at 20:47
  • 2 @isherwood - this doesn't look like a dup of that one. The solution in that case was to add use new Date() instead of just Date(). The OP here was already using new. – jfriend00 Commented May 5, 2014 at 20:50
Add a ment  | 

2 Answers 2

Reset to default 6

You need to use:

new Date().getTime();

instead of

new Date.getTime();

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

new Date.getTime();

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.

When you do:

new Date().getTime();

It is essentially doing this:

(new 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.

You need to instantiate the Date object before invoking methods on it.

Example:

var date = new Date()
start = date.getTime();

http://jsfiddle/3TJLq/

发布评论

评论列表(0)

  1. 暂无评论