- 通过class 关键字创建类, 类名我们还是习惯性定义首字母大写
- 类里面有个constructor 函数,可以接受传递过来的参数,同时返回实例对象
- constructor 函数 只要 new 生成实例时,就会自动调用这个函数, 如果我们不写这个函数,类也会自动生成这个函数
- 生成实例 new 不能省略
- 最后注意语法规范, 创建类 类名后面不要加小括号,生成实例 类名后面加小括号, 构造函数不需要加function
class Person {
constructor(theName, theSex) {
this.name = theName;
this.sex = theSex;
}
}
var per1 = new Person("老黄", 18);
var per2 = new Person("老刘", 15);
console.log(per1);
console.log(per2);
6.在类中添加方法
class Person {
constructor(theName, theSex) {
this.name = theName;
this.sex = theSex;
}
sing(song){
console.log(this.uname + song);
}
}
var per1 = new Person("老黄", 18);
var per2 = new Person("老刘", 15);
console.log(per1);
console.log(per2);
per1.sing('在吃饭')
per2.sing('在工作')
7.继承类
class Father {
constructor(x, y) {
this.x = x;
this.y = y;
}
sum() {
console.log(this.x + this.y);
}
}
class Son extends Father {
constructor(x, y) {
super(x, y); //调用了父类中的构造函数
}
}
var son = new Son(11, 22);
var son1 = new Son(1, 2);
son.sum();
son1.sum();
本文介绍了JavaScript中的类创建和继承概念。通过`class`关键字定义类,并展示了`constructor`构造函数的使用,用于初始化对象属性。此外,还讨论了如何在类中添加方法,例如`sing`方法。最后,通过`extends`关键字演示了类的继承,并调用父类的构造函数`super`。示例中创建了两个Person类的实例并输出,以及Son类从Father类继承并调用`sum`方法的示例。

被折叠的 条评论
为什么被折叠?



