建立Person类,有属性:身高,体重。有方法:运动项目输出,兴趣爱好输出。
新建对象,对象名为自己的名字,实现输出功能。
// 定义 Person 类
class Person {
constructor(height, weight) {
this.height = height;
this.weight = weight;
}
// 运动项目输出
sports() {
console.log("我喜欢跑步和打羽毛球!");
}
// 兴趣爱好输出
hobby() {
console.log("我喜欢看电影、听音乐和旅行!");
}
}
// 新建对象
const person = new Person(170, 65);
// 输出身高和体重
console.log(`我的身高是${person.height},体重是${person.weight}。`);
// 输出运动项目和兴趣爱好
person.sports();
person.hobby();
输出结果:
我的身高是170,体重是65。
我喜欢跑步和打羽毛球!
我喜欢看电影、听音乐和旅行!