admin管理员组文章数量:1356922
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 justDate()
. The OP here was already usingnew
. – jfriend00 Commented May 5, 2014 at 20:50
2 Answers
Reset to default 6You 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/
本文标签: javascriptUndefined is not a function when calling getTime on new DateStack Overflow
版权声明:本文标题:javascript - Undefined is not a function when calling getTime on new Date - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744025350a2577945.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论