定义类 类是’特殊的函数’,两种声明方式,类声明,类表达式 类不存在提升问题,需要先生命,否则会报错 首字母大写
1 2 3 4 5 6 7 8 9 class Super { constructor () { } } const Super = class {} const Super = class Super2 {}
类体和方法定义 {}内为类体,默认严格模式 constructor构造函数,必须有且只能有一个,不写会默认添加
原型方法 1 2 3 4 5 6 7 8 9 10 11 12 13 14 class Super { constructor (a, b) { this .a = a this .b = b } get area () { return this .getArea() } getArea () { return this .a * this .b } } let s = new Super(2 , 5 )s.area
静态方法 static关键字声明
1 2 3 4 5 6 7 class Super { constructor () {} static showArea (a, b) { return a * b } } Super.showArea(2 , 5 )
静态属性和原型属性 必须在类外定义
1 2 3 class Super {}Super.age = '18' Super.prototype.sex = 1
关于this绑定 由于class默认严格模式,当this没有指定时会是undefined而不是global
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 class Super { constructor () {} showThis () { return this } } function Super2 ( ) {}Super2.prototype.showThis = () => { return this } let s = new Super()let s2 = new Super2()let showThis = s.showThislet showThis2 = s2.showThis
extends扩展子类 子类构造函数中须调super() extends也可继承构造函数类
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 class Animal { constructor (name) { this .name = name } wangwang () { console .log(this .name); } } function Animal (name ) { this .name = name } Animal.prototype.wangwang = function ( ) { console .log(this .name); } class Dog extends Animal { constructor (name) { super (name) } ww () { this .wangwang() } } let dog = new Dog('pdd' )dog.ww()