在javascript语言中,生成实例对象使用构造函数;ES6提供了类Class这个概念,作为对象的模板。定义一个类通过class关键字,ES6的类可以看成是构造函数的另一种写法。
如何定义一个类?
1、我们通过class关键字来定义一个类:
- class Person{
- // 类的构造器(必须提供,如果不写,默认提供空的构造器)
- constructor(name,age,weight){
- // 实例私有属性
- this.name = name;
- this.age = age;
- this.weight = weight;
- }
- // 公共方法 ——类似于存在原型对象中
- // Person.prototype
- sayName(){
- console.log(this.name);
- }
-
- // 引用数据类型->实例私有属性
- test = [];
- // 基本数据类型->实例公共属性
- test1 = 'hello';
-
- // 静态属性 由static声明的属性就是静态属性
- static personAttr = '静态属性';
- // 静态方法 由static声明的属性就是静态方法
- static personMethod(){
- console.log('这是我们的静态方法');
- }
- }
-
-
- let p1 = new Person('张三',15,'50kg')
- console.log(p1); //Person { name: '张三', age: 15, weight: '50kg' }
- p1.sayName()//张三
- let p2 = new Person()
- console.log(p1.sayName === p2.sayName);//true
-
- // 静态属性和方法:只能由类本身去调用
- console.log(Person.personAttr); //静态属性
- Person.personMethod() //这是我们的静态方法
-
- console.log(p1.test === p2.test);//false
- console.log(p1.test1 === p2.test1);//true
2、constructor方法是类的默认方法,通过new命令生成对象实例时,自动调用该方法。一个类必须有constructor方法,如果没有显式定义,一个空的constructor方法会被默认添加。constructor里面定义的属性属于实例的私有属性。
3、定义在类体的方法称为实例方法,其实是存在于Person.prototype中,可供所有的实例调用。比如上述的sayName方法就属于公共方法,可供所有实例使用。
定义在类体的属性:如果是引用数据类型,就属于实例的私有属性,比如上述的test;如果是基本数据类型,就属于实例的公共属性,比如上述的test1。
4、通过static关键字来定义静态属性和静态方法。静态属性和静态方法是定义在类上的,所以只能由类本身去调用。在静态方法中,this指向当前类。
ES5实现继承的三种方式
https://blog.csdn.net/LQ313131/article/details/126432548
class可以通过extends关键字实现继承,子类可以没有构造函数,系统会默认分配。子类提供了构造函数则必须要显式调用super。super函数类似于借用构造函数。
实现继承之后:
1、子类对象指向父类对象
console.log(Dog.__proto__ === Animal); //true
2、子类原型对象继承父类原型对象
console.log(Dog.prototype.__proto__ === Animal.prototype); //true
- class Animal{
- constructor(name,age,weight){
- // console.log('父类构造器');
- this.name = name;
- this.age = age;
- this.weight = weight;
- }
- sayName(){
- console.log(this.name);
- }
- static animalAttr = '父类静态方法'
- static animalMethods(d){
- return d instanceof Animal
- }
- }
- // 继承 extends关键字继承 必须显式调用super()
- class Dog extends Animal{
- constructor(name,age,weight,type){
- //使用super调用父类构造器
- super(name,age,weight)
- // console.log('子类构造器');
- this.type = type
- }
- sayName(){
- console.log('这是子类公共方法');
- }
- }
-
-
- let d1 = new Dog('可乐',12,'10kg','金毛')
- console.log(d1);//Dog { name: '可乐', age: 12, weight: '10kg', type: '金毛' }
- //子类的原型对象继承父类的原型对象
- d1.sayName()//这是子类公共方法
- //子类的对象通过__proto__指针指向父类的对象
- console.log(Dog.animalAttr);//父类静态方法
- console.log(Dog.animalMethods(d1));//true