类(class)
(1)在ES5中通过构造函数来模拟类的功能,一般会定义一个构造函数,把一个类的功能进行封装,通过new运算符来调用。
function Person(name,gender){
this.name = name; //this.name的name是类的属性,后面的name是构造函数的形参。
this.gender = gender;
Person.prototype.fun = function(){
console.log(this.name,this.gender);
}
}
var p1 = new Person("张三","男");
p1.fun(); //输出结果为:张三,男
(2)在ES6标准中提供class关键字来定义类,在写法上更简洁,语义性更强。代码如下:
class Person{
constructor(name,gender){ //构造方法
this.name = name;
this.gender = gender;
}
fun(){
console.log(`姓名:${this.name},性别:${this.gender}`);
}
}
let p1 = new Person("关羽","男")
p1.fun();
(3)ES6支持通过getter、setter在原型上定义属性。创建getter的时候需要用关键字get,创建setter的时候需要用关键字set。例如:
class Person{
constructor(name,gender){ //构造方法
this.name = name;
this.gender = gender;
}
get name(){ //用来获取name属性。对象名.name 就会调用该方法
return this._name;
}
set name(newName){ //设置name属性。对象名.name = "值" 就会调用该方法
this._name = newName;
}
fun(){
console.log(`姓名:${this.name},性别:${this.gender}`);
}
}
let p1 = new Person("关羽","男")
console.log(p1.name); //输出结果为关羽
p1.name = "张飞";
console.log(p1.name); //输出结果为张飞
(4)静态成员
在ES5标准中的静态成员,可以通过如下方式实现:
function Student(name){
this.name = name;
}
Student.num = 10;
Student.fun = function(){
console.log(Student.num);
}
var s1 = new Student("张三");
console.log(Student.num); //结果为10
Student.fun(); //结果为10
在ES6标准中使用关键字static来声明静态成员
class Student{
static school = "西安邮电大学"; //静态属性
constructor(name,gender){
this.name = name;
this.gender = gender;
}
display(){
console.log(`学校:${Student.school}, 姓名:${this.name}, 性别:${this.gender}`);
}
}
let s1 = new Student("张三","男");
let s2 = new Student("李四","男");
s1.display();
类的继承
(1)ES6标准中类的继承:通过extends关键字来实现
class Father{
constructor(name){
this.name = name;
}
display(){
console.log(`姓名:${this.name}`);
}
}
class Son extends Father{
constructor(name,height){
super(name);
this.height = height;
}
display(){
super.display();
console.log(`身高:${this.height}`);
}
}
let s1 = new Son("张三","175cm");
s1.display();
在继承中调用super()方法继承父类的 构造方法。super()在使用的过程中需要注意下面两点:
- 在访问this之前要先调用super()
- 如果不调用super(),可以让子类构造函数返还一个对象