为什么(new Date()== new Date())为假,而(Date()== Date())为真?

154 阅读1分钟

情景一:

function isSame (arg1, arg2) {
  return arg1 == arg2
}

let today = Date()
let tomorrow = Date()

console.log(today)
console.log(tomorrow)
console.log(isSame(today, tomorrow))

isSame 返回 true 。 但是,当我使用Date作为构造函数(带有 new)时

情景二:

function isSame (arg1, arg2) {
   return arg1 == arg2
}

let today = new Date()
let tomorrow = new Date()
console.log(isSame(today, tomorrow))

isSame 返回 false 。 但是,当我添加一元运算符 +时

情景三:

function isSame(arg1, arg2) {
    return arg1 ==  arg2
}

let today = + new Date()
let tomorrow = + new Date()

console.log(today)
console.log(tomorrow)
console.log(isSame (today, tomorrow))

为什么以上几种情况返回的不同呢?

  • 推荐答案

使用 Date(),JavaScript Date对象只能可以通过调用JavaScript Date作为构造函数实例化:作为常规函数调用(即不使用new运算符)将返回字符串,而不是Date对象。

typeof new Date() === 'object'
typeof Date() === 'string'