建立Person类,有属性:身高,体重。有方法:运动项目输出,兴趣爱好输出。
新建对象,对象名为自己的名字,实现输出功能。
// 定义Person类
class Person {
constructor(height, weight) {
this.height = height;
this.weight = weight;
}
// 运动项目输出方法
showSport() {
console.log("喜欢跑步和游泳。");
}
// 兴趣爱好输出方法
showHobby() {
console.log("喜欢听音乐、看电影、旅游。");
}
}
// 创建新对象,对象名为自己的名字(假设名字为Alice),身高为165,体重为55
const Alice = new Person(165, 55);
// 调用运动项目输出方法
Alice.showSport(); // 输出:"喜欢跑步和游泳。"
// 调用兴趣爱好输出方法
Alice.showHobby(); // 输出:"喜欢听音乐、看电影、旅游。"