ES6的类 ECMAScript 2015 中引入的 JavaScript 类实质上是 JavaScript 现有的基于原型的继承的语法糖。类语法不会 为JavaScript引入新的面向对象的继承模型。
1. 定义类 类实际上是个“特殊的函数 ”,就像你能够定义的函数表达式 和函数声明 一样,类语法有两个组成部分:类表达式 和类声明 。一个类的类体是一对花括号/大括号 {} 中的部分。这是你定义类成员的位置,如方法或构造函数。
1、类声明:要声明一个类,你可以使用带有class关键字的类名(这里是“Rectangle”)。
1 2 3 4 5 class Rectangle { constructor (height, width ) { this .height = height; } } let re = new Rectangle (20 );console .log (re.height )
函数声明 和类声明 之间的一个重要区别是函数声明会提升 ,类声明不会。你首先需要声明你的类,然后访问它,否则代码会抛出一个ReferenceError 。
2、类表达式:类表达式可以是具名的或匿名的,一个具名类表达式的名称是类内的一个局部属性,它可以通过类本身(而不是类实例)的name 属性来获取。
1 2 3 4 5 6 7 8 9 10 let Rectangle = class { constructor (height, width ) { this .height = height; } }; console .log (Rectangle .name );let Rectangle = class Rectangle2 { constructor (height, width ) { this .height = height; } }; console .log (Rectangle .name );
类表达式也会有类型提升的限制。
2. 注意点 2.1 严格模式 类和模块的内部,默认就是严格模式 ,所以不需要使用use strict指定运行模式。只要你的代码写在类或模块之中,就只有严格模式可用。考虑到未来所有的代码,其实都是运行在模块之中,所以 ES6 实际上把整个语言升级到了严格模式。
2.2 类不存在变量提升 1 2 new Foo (); class Foo {}
类不存在变量提升(hoist),这一点与 ES5 完全不同。因为 ES6 不会把类的声明提升到代码头部。这种规定的原因与下文要提到的继承有关,必须保证子类在父类之后定义。
1 2 3 4 { let Foo = class {}; class Bar extends Foo { } }
上面的代码不会报错,因为Bar继承Foo的时候,Foo已经有定义了。但是,如果存在class的提升,上面代码就会报错,因为class会被提升到代码头部,而let命令是不提升的,所以导致Bar继承Foo的时候,Foo还没有定义。
2.3 name属性 由于本质上,ES6 的类只是 ES5 的构造函数的一层包装,所以函数的许多特性都被Class继承,包括name属性。
1 2 class Point {}Point .name
2.4 this的指向 类的方法内部如果含有this,它默认指向类的实例。但是,一旦单独使用该方法,那么“this”值在被调用的函数内部将为 undefined 。不会发生自动包装。因为所有的函数、方法、构造函数、getters或setters都在严格模式下执行。因此如果我们没有指定this的值,this值将为undefined。
1 2 3 4 5 6 7 8 9 10 class Animal { speak ( ) { console .log (this ); } static eat ( ) { console .log (this ); } } (new Animal ()).speak (); let speak = (new Animal ()).speak ;speak (); Animal .eat () let eat = Animal .eat ;eat ();
如果我们使用传统的基于函数的类来编写上述代码,那么基于调用该函数的“this”值将发生自动装箱。
1 2 3 4 5 6 7 function Animal ( ) { }Animal .prototype .speak = function ( ) {console .log (this );}Animal .eat = function ( ) { console .log (this ); }let speak = (new Animal ()).speak ;speak (); let eat = Animal .eat ;eat ();
一个比较简单的解决方法是,在构造方法中绑定this,这样就不会找不到print方法了。
1 2 3 4 5 6 7 8 9 10 class Logger { constructor ( ) { this .printName = this .printName .bind (this ); } printName (name = 'there' ) { this .print (`Hello ${name} ` );} print (text ) { console .log (text); } } const logger = new Logger ();const { printName } = logger;printName ();
另一种解决方法是使用箭头函数。箭头函数内部的this总是指向定义时所在的对象。
1 2 3 4 5 6 7 8 9 class Logger { printName = (name = 'there' ) => { this .print (`Hello ${name} ` );} print (text ) { console .log (text); } eat ( ) {console .log (this )} } const logger = new Logger ();const { printName, eat } = logger;printName (); eat ()
2.5 constructor构造函数 constructor方法是类的默认方法,通过new命令生成对象实例时,自动调用该方法。一个类必须有constructor方法,如果没有显式定义,一个空的constructor方法会被默认添加。constructor方法默认返回实例对象(即this),完全可以指定返回另外一个对象。
一个类只能拥有一个名为 “constructor”的特殊方法。如果类包含多个constructor的方法,则将抛出 一个SyntaxError 。一个构造函数可以使用 super 关键字来调用一个父类的构造函数。
类必须使用new调用,否则会报错。这是它跟普通构造函数的一个主要区别,后者不用new也可以执行。
1 2 3 4 5 6 7 8 9 10 class Point { }class Point { constructor ( ) {} }class Foo { constructor ( ) { return Object .create (null ); } } new Foo () instanceof Foo Foo ()
2.6 取值函数(getter)和存值函数(setter) 与 ES5 一样,在“类”的内部可以使用get和set关键字,对某个属性设置存值函数和取值函数,拦截该属性的存取行为。
1 2 3 4 5 6 7 8 9 class MyClass { get prop () {return 'getter' ;} set prop (value ) {console .log ('setter: ' +value);} } let inst = new MyClass ();inst.prop = 123 ; inst.prop
2.7 属性表达式 类的属性名,可以采用表达式。
1 2 3 4 5 6 7 8 9 let propsName = 'jack' let propsFunc = 'sayHello' class People { constructor (name ) { this [propsName] = name } [propsFunc]() { console .log (this [propsName] + ': hello' ) } } let jack = new People ('sun' )jack.sayHello () jack[propsFunc]()
2.8 new.target属性 new是从构造函数生成实例对象的命令。ES6 为new命令引入了一个new.target属性,该属性一般用在构造函数之中,返回new命令作用于的那个构造函数。如果构造函数不是通过new命令或Reflect.construct()调用的,new.target会返回undefined,因此这个属性可以用来确定构造函数是怎么调用的。
Class 内部调用new.target,返回当前 Class。
1 2 3 4 5 6 class Rectangle { constructor (length, width ) { console .log (new .target === Rectangle ); } } var obj = new Rectangle ();
需要注意的是,子类继承父类时,new.target会返回子类。利用这个特点,可以写出不能独立使用、必须继承后才能使用的类。
1 2 3 4 5 6 7 8 class Shape { constructor ( ) { if (new .target === Shape ) { throw new Error ('本类不能实例化' ); } } } class Rectangle extends Shape { constructor (length, width ) { super (); } }var x = new Shape (); var y = new Rectangle (3 , 4 );
3. 实例方法定义 ES6 的类,完全可以看作构造函数的另一种写法。构造函数的prototype属性,在 ES6 的“类”上面继续存在。类的所有方法都定义在类的prototype属性上面。在类的实例上面调用方法,其实就是调用原型上的方法。所以类的新方法可以添加在prototype对象上面。Object.assign方法可以很方便地一次向类添加多个方法。
另外,类的内部所有定义的方法,都是不可枚举的。而ES5中是可以枚举的。
方法定义使用新的方式:https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Functions/Method_definitions
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 26 27 28 29 class Point { }typeof Point Point === Point .prototype .constructor class Point { constructor ( ) { } toString ( ) { } toValue ( ) {} }Point .prototype = { constructor ( ) {}, toString ( ) {}, toValue ( ) {}, };class B { sayHello ( ){} }let b = new B ();b.sayHello === B.prototype .sayHello class Point { constructor ( ){ } }Object .assign (Point .prototype , { toString ( ){}, toValue ( ){} }); Object .keys (Point .prototype ) Object .getOwnPropertyNames (Point .prototype ) function People ( ) {}People .prototype .toString = function ( ) {}Object .keys (People .prototype ) Object .getOwnPropertyNames (People .prototype )
4. 实例属性定义 实例的属性必须定义在类的方法里,静态的或原型的数据属性必须定义在类定义的外面。
1 2 3 4 5 6 7 8 class Rectangle { constructor (height, width ) { this .height = height; this .width = width; } } Rectangle .staticWidth = 20 ;Rectangle .prototype .prototypeWidth = 25 ;
字段声明:公共和私有字段声明是JavaScript标准委员会TC39 提出的实验性功能(第3阶段) 。浏览器中的支持是有限的,但是可以通过Babel 等系统构建后使用此功能。
4.1 公有字段声明 使用JavaScript字段声明语法,上面的示例可以写成:
1 2 3 4 5 6 7 8 class Rectangle { height = 0; width; constructor(height, width) { this.height = height; this.width = width; } }
通过预先声明字段,类定义变得更加自我记录,并且字段始终存在。
正如上面看到的,这个字段可以用也可以不用默认值来声明。
4.2 私有字段声明 使用私有字段,可以按以下方式细化定义。
1 2 3 4 5 6 7 8 class Rectangle { #height = 0; #width; constructor(height, width) { this.#height = height; this.#width = width; } }
从类外部引用私有字段是错误的。它们只能在类里面中读取或写入。通过定义在类外部不可见的内容,可以确保类的用户不会依赖于内部,因为内部可能在不同版本之间发生变化。
私有字段仅能在字段声明中预先定义。
私有字段不能通过在之后赋值来创建它们,这种方式只适用普通属性。
更多信息,请看class fields .
5. 类的实例 生成类的实例的写法,与 ES5 完全一样,也是使用new命令。前面说过,如果忘记加上new,像函数那样调用Class,将会报错。与 ES5 一样,实例的属性除非显式定义在其本身(即定义在this对象上),否则都是定义在原型上(即定义在class上)。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 class Point { constructor (x, y ) { this .x = x; this .y = y; } toString ( ) { return '(' + this .x + ', ' + this .y + ')' ; } } var point = Point (2 , 3 );var point = new Point (2 , 3 );point.toString () point.hasOwnProperty ('x' ) point.hasOwnProperty ('y' ) point.hasOwnProperty ('toString' ) point.__proto__ .hasOwnProperty ('toString' )
与 ES5 一样,类的所有实例共享一个原型对象。
1 2 3 4 5 6 7 8 9 10 class Point {}var p1 = new Point (2 ,3 );var p2 = new Point (3 ,2 );p1.__proto__ === p2.__proto__ p1.__proto__ .printName = function ( ) { return 'Oops' }; p1.printName () p2.printName () var p3 = new Point (4 ,2 );p3.printName ()
上面代码中,p1和p2都是Point的实例,它们的原型都是Point.prototype,所以__proto__属性是相等的。这也意味着,可以通过实例的__proto__属性为“类”添加方法。__proto__ 并不是语言本身的特性,这是各大厂商具体实现时添加的私有属性,虽然目前很多现代浏览器的 JS 引擎中都提供了这个私有属性,但依旧不建议在生产中使用该属性,避免对环境产生依赖。可以使用 Object.getPrototypeOf 方法来获取实例对象的原型,然后再来为原型添加方法/属性。
6. 静态方法 static 关键字用来定义一个类的一个静态方法。调用静态方法不需要实例化 该类,但不能通过一个类实例调用静态方法。静态方法通常用于为一个应用程序创建工具函数。
1 2 3 4 class Foo { static classMethod ( ) { return 'hello' ; } }Foo .classMethod () var foo = new Foo ();foo.classMethod ()
注意,如果静态方法包含this关键字,这个this指的是类,而不是实例。
1 2 3 4 5 6 class Foo { static bar ( ) { this .baz (); } static baz ( ) { console .log ('hello' ); } baz ( ) { console .log ('world' ); } } Foo .bar ()
父类的静态方法,可以被子类继承。静态方法也是可以从super对象上调用的。
1 2 3 4 5 6 7 8 9 class Foo { static hello ( ) { return 'hello' ; } } class Bar extends Foo { static classMethod ( ) { return super .hello () + ', too' ; } } console .log (Bar .hello ()) console .log (Bar .classMethod ())
7. 静态属性 静态属性指的是 Class 本身的属性,即Class.propName,而不是定义在实例对象(this)上的属性。目前,只有这种写法可行,因为 ES6 明确规定,Class 内部只有静态方法,没有静态属性。
1 2 3 class Foo { }Foo .prop = 1 ;Foo .prop
现在有一个提案 提供了类的静态属性,写法是在实例属性的前面,加上static关键字。
1 2 3 4 5 class MyClass { static myStaticProp = 42 ; constructor ( ) { console .log (MyClass .myStaticProp ); } } new MyClass ()
8. 使用extends实现继承 Class 可以通过extends关键字实现继承,这比 ES5 的通过修改原型链实现继承,要清晰和方便很多。
如果子类中定义了构造函数,那么它必须先调用 super() 才能在构造函数中使用 this ,否则新建实例时会报错。这是因为子类自己的this对象,必须先通过父类的构造函数完成塑造,得到与父类同样的实例属性和方法,然后再对其进行加工,加上子类自己的实例属性和方法。如果不调用super方法,子类就得不到this对象。
ES5 的继承,实质是先创造子类的实例对象this,然后再将父类的方法添加到this上面(Parent.apply(this))。ES6 的继承机制完全不同,实质是先将父类实例对象的属性和方法,加到this上面(所以必须先调用super方法),然后再用子类的构造函数修改this。
1 2 3 4 5 6 7 8 9 10 class Animal { constructor (name ) { this .name = name; } speak ( ) { console .log (this .name + ' makes a noise.' ); } } class Dog extends Animal { constructor (name, color ) {super (name); this .color = color; } speak ( ) { console .log (this .name + ' barks.' + this .color ); } } var d = new Dog ('Mitzie' , 'red' );d.speak ();
也可以继承传统的基于函数的“类”:
1 2 3 4 5 6 7 8 function Animal (name) { this .name = name; }Animal .prototype .speak = function ( ) { console .log (this .name + ' makes a noise.' ); }class Dog extends Animal { speak ( ) { super .speak (); console .log (this .name + ' barks.' ); } } var d = new Dog ('Mitzie' );d.speak ();
请注意,类不能继承常规对象(不可构造的)。如果要继承常规对象,可以改用Object.setPrototypeOf() :
1 2 3 4 5 6 7 var Animal = { speak ( ) { console .log (this .name + ' makes a noise.' ); } }; class Dog { constructor (name ) { this .name = name; } }Object .setPrototypeOf (Dog .prototype , Animal );var d = new Dog ('Mitzie' );d.speak ();
9. super关键字 super这个关键字,既可以当作函数使用,也可以当作对象使用。在这两种情况下,它的用法完全不同。
注意,使用super的时候,必须显式指定是作为函数、还是作为对象使用,否则会报错。
第一种情况,super作为函数调用时,代表父类的构造函数。ES6 要求,子类的构造函数必须执行一次super函数。作为函数时,super()只能用在子类的构造函数之中,用在其他地方就会报错。
1 2 3 4 5 class A {}class B extends A { constructor ( ) { super (); } m ( ) { super (); } }
第二种情况,super作为对象时,在普通方法中,指向父类的原型对象;在静态方法中,指向父类。
1 2 3 4 5 6 7 class A { p ( ) { return 2 ; } }class B extends A { constructor ( ) { super (); console .log (super .p ()); } } let b = new B ();
子类B当中的super.p(),就是将super当作一个对象使用。这时,super在普通方法之中,指向A.prototype,所以super.p()就相当于A.prototype.p()。
这里需要注意,由于super指向父类的原型对象,所以定义在父类实例上的方法或属性,是无法通过super调用的。如果属性定义在父类的原型对象上,super就可以取到。
1 2 3 4 5 6 class A { constructor ( ) { this .p = 2 ; } }A.prototype .x = 2 ; class B extends A { get m () { return super .p ; } get x () { return super .x ; }}let b = new B ();b.m b.x
ES6 规定,在子类普通方法中通过super调用父类的方法时,方法内部的this指向当前的子类实例。所以如果通过super对某个属性赋值,这时super就是this,赋值的属性会变成子类实例的属性。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 class A { constructor ( ) { this .x = 1 ; } print ( ) { console .log (this .x ); } } class B extends A { constructor ( ) { super (); this .x = 2 ; } m ( ) { super .print (); } p ( ) { super .x = 300 ; console .log (super .x ); console .log (this .x ); } } let b = new B ();b.m () b.p ()
如果super作为对象,用在静态方法之中,这时super将指向父类,而不是父类的原型对象。另外,在子类的静态方法中通过super调用父类的方法时,方法内部的this指向当前的子类,而不是子类的实例。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 class A { constructor ( ) { this .x = 1 ; } static myMethod (msg ) { console .log ('static' , msg); } myMethod (msg ) { console .log ('instance' , msg); } static print ( ) { console .log (this .x ); } } class B extends A { static myMethod (msg ) {super .myMethod (msg);} myMethod (msg ) {super .myMethod (msg);} static m ( ) { super .print (); } } B.myMethod (1 ); var b = new B ();b.myMethod (2 ); B.x = 5000 ; B.m ()
最后,由于对象总是继承其他对象的,所以可以在任意一个对象中,使用super关键字。
1 2 3 4 5 var obj = { toString ( ) { return "MyObject: " + super .toString (); } }; obj.toString ();
参考资料 类 MDN
类元素 MDN
Class 的基本语法 ES6 阮一峰
Class 的继承 ES6 阮一峰