W3School TIY Editor
W3School 在线教程
改变方向
暗黑模式
运行代码
<!DOCTYPE html> <html> <body> <h1>JavaScript 类方法</h1> <p>如何定义和使用类方法。</p> <p id="demo"></p> <script> class Car { constructor(name, year) { this.name = name; this.year = year; } age() { let date = new Date(); return date.getFullYear() - this.year; } } let myCar = new Car("Ford", 2014); document.getElementById("demo").innerHTML = "My car is " + myCar.age() + " years old."; </script> </body> </html>