类的方法
我们使用关键字 class 创建一个类,可以添加一个 constructor() 方法,然后添加任意数量的方法。
classClassName{ constructor(){ ... } method_1(){ ... } method_2(){ ... } method_3(){ ... }}
以下实例我们创建一个 "age" 方法,用于返回网站年龄:
实例
classRunoob{ constructor(name, year){ this.name = name; this.year = year; } age(){ letdate = newDate(); returndate.getFullYear() - this.year; }}letrunoob = newRunoob("教程", 2018);document.getElementById("demo").innerHTML ="教程 " + runoob.age() + " 岁了。";
我们还可以向类的方法发送参数:
实例
classRunoob{ constructor(name, year){ this.name = name; this.year = year; } age(x){ returnx - this.year; }}letdate = newDate();letyear = date.getFullYear(); letrunoob = newRunoob("教程", 2020);document.getElementById("demo").innerHTML="教程 " + runoob.age(year) + " 岁了。";