- 通过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();