构造函数 returns 在 JS 中未定义

Constructor returns undefined in JS

我试图让当前日期显示在 HTML 但它显示为未定义。尽管控制台以正确的形式 return 日期,但控制台中没有弹出任何错误。我不确定我做错了什么。

// get date
var today = new Date();
var date = (today.getMonth()+1)+'-'+today.getDate()+'-'+today.getFullYear();
document.getElementsByClassName('date').innerHTML = date;
console.log(date);

// think there is something wrong with this constructor because right now the selected HTML element returns undefined 
class Note {
  constructor(title, body, date){
    this.title = title;
    this.body = body;
    this.date = date;
    this.id = Math.random();
  }
}

这是HTML

<h3 class = "date">${note.date}</h3>

你应该有这样的东西:

class Note {
    constructor(title, body, date){
        this.title = title;
        this.body = body;
        this.date = date;
        this.id = Math.random();
    }
}

const today = new Date();
const date = `${today.getMonth() + 1}-${today.getDate()}-${today.getFullYear()}`;
const note = new Note("Some Title", "Some Body", date);
document.querySelector("span").innerText = note.date;
<span></span>

或者像这样:

class Note {

    id = -1;

    constructor(title, body) {
        this.title = title;
        this.body = body;
        this.date = new Date().toDateString();
        this.id ++;
    }
}

const { title, body, date, id } = new Note("Some Title", "Some Body");
document.querySelector("div").innerHTML = `
    <h1>${title}</h1>
    <p>${body}</p>
    <small>${date}</small>
    <br />
    <b>ID: ${id}</b>
`;
<div></div>

希望你能在这里得到这个想法

let note = new Note("title" , "body" , date);

console.log(note.date , note.body , note.title)