2

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);
cookie monster
  • 10,671
  • 4
  • 31
  • 45
JimmyRare
  • 3,958
  • 2
  • 20
  • 23
  • On which line do you get that error? – jfriend00 May 05 '14 at 20:46
  • 1
    possible duplicate of [javascript Date().getTime() is not a function](http://stackoverflow.com/questions/10395242/javascript-date-gettime-is-not-a-function) – isherwood May 05 '14 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 May 05 '14 at 20:50

2 Answers2

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.

jfriend00
  • 683,504
  • 96
  • 985
  • 979
1

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

Example:

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

http://jsfiddle.net/3TJLq/

Robin Drexler
  • 4,307
  • 3
  • 25
  • 28