首页 > 解决方案 > 构造函数在 JS 中返回 undefined

问题描述

我试图让当前日期显示在 HTML 上,但它显示为未定义。控制台确实以正确的形式返回日期,并且控制台中没有弹出错误。我不确定我做错了什么。

// 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>

标签: javascriptdateconstructorthis

解决方案


你应该有这样的东西:

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>

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


推荐阅读