es6中class学习

1、Class基本语法

概述

JavaScript语言的传统方法是通过构造函数,定义并生成新对象。下面是一个例子。

[html]  view plain  copy
  1. function Point(x, y) {  
  2.   this.x = x;  
  3.   this.y = y;  
  4. }  
  5.   
  6. Point.prototype.toString = function () {  
  7.   return '(' + this.x + ', ' + this.y + ')';  
  8. };  
  9.   
  10. var p = new Point(1, 2);  

上面这种写法跟传统的面向对象语言(比如C++和Java)差异很大,很容易让新学习这门语言的程序员感到困惑。

ES6提供了更接近传统语言的写法,引入了Class(类)这个概念,作为对象的模板。通过class关键字,可以定义类。基本上,ES6的class可以看作只是一个语法糖,它的绝大部分功能,ES5都可以做到,新的class写法只是让对象原型的写法更加清晰、更像面向对象编程的语法而已。上面的代码用ES6的“类”改写,就是下面这样。

[html]  view plain  copy
  1. //定义类  
  2. class Point {  
  3.   constructor(x, y) {  
  4.     this.x = x;  
  5.     this.y = y;  
  6.   }  
  7.   
  8.   toString() {  
  9.     return '(' + this.x + ', ' + this.y + ')';  
  10.   }  
  11. }  

上面代码定义了一个“类”,可以看到里面有一个constructor方法,这就是构造方法,而this关键字则代表实例对象。也就是说,ES5的构造函数Point,对应ES6的Point类的构造方法。

Point类除了构造方法,还定义了一个toString方法。注意,定义“类”的方法的时候,前面不需要加上function这个关键字,直接把函数定义放进去了就可以了。另外,方法之间不需要逗号分隔,加了会报错。

ES6的类,完全可以看作构造函数的另一种写法。

[html]  view plain  copy
  1. class Point {  
  2.   // ...  
  3. }  
  4.   
  5. typeof Point // "function"  
  6. Point === Point.prototype.constructor // true  

上面代码表明,类的数据类型就是函数,类本身就指向构造函数。

使用的时候,也是直接对类使用new命令,跟构造函数的用法完全一致。

[html]  view plain  copy
  1. class Bar {  
  2.   doStuff() {  
  3.     console.log('stuff');  
  4.   }  
  5. }  
  6.   
  7. var b = new Bar();  
  8. b.doStuff() // "stuff"  
构造函数的 prototype 属性,在ES6的“类”上面继续存在。事实上,类的所有方法都定义在类的 prototype 属性上面。
[html]  view plain  copy
  1. class Point {  
  2.   constructor(){  
  3.     // ...  
  4.   }  
  5.   
  6.   toString(){  
  7.     // ...  
  8.   }  
  9.   
  10.   toValue(){  
  11.     // ...  
  12.   }  
  13. }  
  14.   
  15. // 等同于  
  16.   
  17. Point.prototype = {  
  18.   toString(){},  
  19.   toValue(){}  
  20. };  

在类的实例上面调用方法,其实就是调用原型上的方法。

[html]  view plain  copy
  1. class B {}  
  2. let b = new B();  
  3.   
  4. b.constructor === B.prototype.constructor // true  

上面代码中,b是B类的实例,它的constructor方法就是B类原型的constructor方法。

由于类的方法都定义在prototype对象上面,所以类的新方法可以添加在prototype对象上面。Object.assign方法可以很方便地一次向类添加多个方法。

[html]  view plain  copy
  1. class Point {  
  2.   constructor(){  
  3.     // ...  
  4.   }  
  5. }  
  6.   
  7. Object.assign(Point.prototype, {  
  8.   toString(){},  
  9.   toValue(){}  
  10. });  
prototype 对象的 constructor 属性,直接指向“类”的本身,这与ES5的行为是一致的。
[html]  view plain  copy
  1. Point.prototype.constructor === Point // true  

另外,类的内部所有定义的方法,都是不可枚举的(non-enumerable)。

[html]  view plain  copy
  1. class Point {  
  2.   constructor(x, y) {  
  3.     // ...  
  4.   }  
  5.   
  6.   toString() {  
  7.     // ...  
  8.   }  
  9. }  
  10.   
  11. Object.keys(Point.prototype)  
  12. // []  
  13. Object.getOwnPropertyNames(Point.prototype)  
  14. // ["constructor","toString"]  
上面代码中, toString 方法是 Point 类内部定义的方法,它是不可枚举的。这一点与ES5的行为不一致。
[html]  view plain  copy
  1. var Point = function (x, y) {  
  2.   // ...  
  3. };  
  4.   
  5. Point.prototype.toString = function() {  
  6.   // ...  
  7. };  
  8.   
  9. Object.keys(Point.prototype)  
  10. // ["toString"]  
  11. Object.getOwnPropertyNames(Point.prototype)  
  12. // ["constructor","toString"]  

上面代码采用ES5的写法,toString方法就是可枚举的。

类的属性名,可以采用表达式。

[html]  view plain  copy
  1. let methodName = "getArea";  
  2. class Square{  
  3.   constructor(length) {  
  4.     // ...  
  5.   }  
  6.   
  7.   [methodName]() {  
  8.     // ...  
  9.   }  
  10. }  

上面代码中,Square类的方法名getArea,是从表达式得到的。


constructor方法
constructor 方法是类的默认方法,通过 new 命令生成对象实例时,自动调用该方法。一个类必须有 constructor 方法,如果没有显式定义,一个空的 constructor 方法会被默认添加。
[html]  view plain  copy
  1. constructor() {}  

constructor方法默认返回实例对象(即this),完全可以指定返回另外一个对象。

[html]  view plain  copy
  1. class Foo {  
  2.   constructor() {  
  3.     return Object.create(null);  
  4.   }  
  5. }  
  6.   
  7. new Foo() instanceof Foo  
  8. // false  

上面代码中,constructor函数返回一个全新的对象,结果导致实例对象不是Foo类的实例。

类的构造函数,不使用new是没法调用的,会报错。这是它跟普通构造函数的一个主要区别,后者不用new也可以执行。

[html]  view plain  copy
  1. class Foo {  
  2.   constructor() {  
  3.     return Object.create(null);  
  4.   }  
  5. }  
  6.   
  7. Foo()  
  8. // TypeError: Class constructor Foo cannot be invoked without 'new'  

类的实例对象
生成类的实例对象的写法,与ES5完全一样,也是使用 new 命令。如果忘记加上 new ,像函数那样调用 Class ,将会报错。
[html]  view plain  copy
  1. // 报错  
  2. var point = Point(2, 3);  
  3.   
  4. // 正确  
  5. var point = new Point(2, 3);  
与ES5一样,实例的属性除非显式定义在其本身(即定义在 this 对象上),否则都是定义在原型上(即定义在 class 上)。
[html]  view plain  copy
  1. //定义类  
  2. class Point {  
  3.   
  4.   constructor(x, y) {  
  5.     this.x = x;  
  6.     this.y = y;  
  7.   }  
  8.   
  9.   toString() {  
  10.     return '(' + this.x + ', ' + this.y + ')';  
  11.   }  
  12.   
  13. }  
  14.   
  15. var point = new Point(2, 3);  
  16.   
  17. point.toString() // (2, 3)  
  18.   
  19. point.hasOwnProperty('x') // true  
  20. point.hasOwnProperty('y') // true  
  21. point.hasOwnProperty('toString') // false  
  22. point.__proto__.hasOwnProperty('toString') // true  

上面代码中,xy都是实例对象point自身的属性(因为定义在this变量上),所以hasOwnProperty方法返回true,而toString是原型对象的属性(因为定义在Point类上),所以hasOwnProperty方法返回false。这些都与ES5的行为保持一致。

与ES5一样,类的所有实例共享一个原型对象。

[html]  view plain  copy
  1. var p1 = new Point(2,3);  
  2. var p2 = new Point(3,2);  
  3.   
  4. p1.__proto__ === p2.__proto__  
  5. //true  

上面代码中,p1p2都是Point的实例,它们的原型都是Point,所以__proto__属性是相等的。

这也意味着,可以通过实例的__proto__属性为Class添加方法。

[html]  view plain  copy
  1. var p1 = new Point(2,3);  
  2. var p2 = new Point(3,2);  
  3.   
  4. p1.__proto__.printName = function () { return 'Oops' };  
  5.   
  6. p1.printName() // "Oops"  
  7. p2.printName() // "Oops"  
  8.   
  9. var p3 = new Point(4,2);  
  10. p3.printName() // "Oops"  
上面代码在 p1 的原型上添加了一个 printName 方法,由于 p1 的原型就是 p2 的原型,因此 p2 也可以调用这个方法。而且,此后新建的实例 p3 也可以调用这个方法。这意味着,使用实例的 __proto__ 属性改写原型,必须相当谨慎,不推荐使用,因为这会改变Class的原始定义,影响到所有实例。

不存在变量提升

Class不存在变量提升(hoist),这一点与ES5完全不同。

[html]  view plain  copy
  1. new Foo(); // ReferenceError  
  2. class Foo {}  
上面代码中,Foo类使用在前,定义在后,这样会报错,因为ES6不会把类的声明提升到代码头部。这种规定的原因与下文要提到的继承有关,必须保证子类在父类之后定义。
[html]  view plain  copy
  1. {  
  2.   let Foo = class {};  
  3.   class Bar extends Foo {  
  4.   }  
  5. }  
上面的代码不会报错,因为class继承Foo的时候,Foo已经有定义了。但是,如果存在class的提升,上面代码就会报错,因为class会被提升到代码头部,而let命令是不提升的,所以导致class继承Foo的时候,Foo还没有定义。

Class表达式

与函数一样,类也可以使用表达式的形式定义。

[html]  view plain  copy
  1. const MyClass = class Me {  
  2.   getClassName() {  
  3.     return Me.name;  
  4.   }  
  5. };  
上面代码使用表达式定义了一个类。需要注意的是,这个类的名字是 MyClass 而不是 Me Me 只在Class的内部代码可用,指代当前类。
[html]  view plain  copy
  1. let inst = new MyClass();  
  2. inst.getClassName() // Me  
  3. Me.name // ReferenceError: Me is not defined  

上面代码表示,Me只在Class内部有定义。

如果类的内部没用到的话,可以省略Me,也就是可以写成下面的形式。

[html]  view plain  copy
  1. const MyClass = class { /* ... */ };  

采用Class表达式,可以写出立即执行的Class。

[html]  view plain  copy
  1. let person = new class {  
  2.   constructor(name) {  
  3.     this.name = name;  
  4.   }  
  5.   
  6.   sayName() {  
  7.     console.log(this.name);  
  8.   }  
  9. }('张三');  
  10.   
  11. person.sayName(); // "张三"  

上面代码中,person是一个立即执行的类的实例。


私有方法

私有方法是常见需求,但ES6不提供,只能通过变通方法模拟实现。

一种做法是在命名上加以区别。

[html]  view plain  copy
  1. class Widget {  
  2.   
  3.   // 公有方法  
  4.   foo (baz) {  
  5.     this._bar(baz);  
  6.   }  
  7.   
  8.   // 私有方法  
  9.   _bar(baz) {  
  10.     return this.snaf = baz;  
  11.   }  
  12.   
  13.   // ...  
  14. }  

上面代码中,_bar方法前面的下划线,表示这是一个只限于内部使用的私有方法。但是,这种命名是不保险的,在类的外部,还是可以调用到这个方法。

另一种方法就是索性将私有方法移出模块,因为模块内部的所有方法都是对外可见的。

[html]  view plain  copy
  1. class Widget {  
  2.   foo (baz) {  
  3.     bar.call(this, baz);  
  4.   }  
  5.   
  6.   // ...  
  7. }  
  8.   
  9. function bar(baz) {  
  10.   return this.snaf = baz;  
  11. }  

上面代码中,foo是公有方法,内部调用了bar.call(this, baz)。这使得bar实际上成为了当前模块的私有方法。

还有一种方法是利用Symbol值的唯一性,将私有方法的名字命名为一个Symbol值。

[html]  view plain  copy
  1. const bar = Symbol('bar');  
  2. const snaf = Symbol('snaf');  
  3.   
  4. export default class myClass{  
  5.   
  6.   // 公有方法  
  7.   foo(baz) {  
  8.     this[bar](baz);  
  9.   }  
  10.   
  11.   // 私有方法  
  12.   [bar](baz) {  
  13.     return this[snaf] = baz;  
  14.   }  
  15.   
  16.   // ...  
  17. };  
上面代码中, bar snaf 都是 Symbol 值,导致第三方无法获取到它们,因此达到了私有方法和私有属性的效果。

this的指向
类的方法内部如果含有 this ,它默认指向类的实例。但是,必须非常小心,一旦单独使用该方法,很可能报错。
[html]  view plain  copy
  1. class Logger {  
  2.   printName(name = 'there') {  
  3.     this.print(`Hello ${name}`);  
  4.   }  
  5.   
  6.   print(text) {  
  7.     console.log(text);  
  8.   }  
  9. }  
  10.   
  11. const logger = new Logger();  
  12. const { printName } = logger;  
  13. printName(); // TypeError: Cannot read property 'print' of undefined  

上面代码中,printName方法中的this,默认指向Logger类的实例。但是,如果将这个方法提取出来单独使用,this会指向该方法运行时所在的环境,因为找不到print方法而导致报错。

一个比较简单的解决方法是,在构造方法中绑定this,这样就不会找不到print方法了。

[html]  view plain  copy
  1. class Logger {  
  2.   constructor() {  
  3.     this.printName = this.printName.bind(this);  
  4.   }  
  5.   
  6.   // ...  
  7. }  

另一种解决方法是使用箭头函数。

[html]  view plain  copy
  1. class Logger {  
  2.   constructor() {  
  3.     this.printName = (name = 'there') => {  
  4.       this.print(`Hello ${name}`);  
  5.     };  
  6.   }  
  7.   
  8.   // ...  
  9. }  

还有一种解决方法是使用Proxy,获取方法的时候,自动绑定this

[html]  view plain  copy
  1. function selfish (target) {  
  2.   const cache = new WeakMap();  
  3.   const handler = {  
  4.     get (target, key) {  
  5.       const value = Reflect.get(target, key);  
  6.       if (typeof value !== 'function') {  
  7.         return value;  
  8.       }  
  9.       if (!cache.has(value)) {  
  10.         cache.set(value, value.bind(target));  
  11.       }  
  12.       return cache.get(value);  
  13.     }  
  14.   };  
  15.   const proxy = new Proxy(target, handler);  
  16.   return proxy;  
  17. }  
  18.   
  19. const logger = selfish(new Logger());  

严格模式

类和模块的内部,默认就是严格模式,所以不需要使用use strict指定运行模式。只要你的代码写在类或模块之中,就只有严格模式可用。

考虑到未来所有的代码,其实都是运行在模块之中,所以ES6实际上把整个语言升级到了严格模式。


name属性
由于本质上,ES6的类只是ES5的构造函数的一层包装,所以函数的许多特性都被 Class 继承,包括 name 属性。
[html]  view plain  copy
  1. class Point {}  
  2. Point.name // "Point"  

name属性总是返回紧跟在class关键字后面的类名。


2、Class的继承
基本用法
Class之间可以通过 extends 关键字实现继承,这比ES5的通过修改原型链实现继承,要清晰和方便很多。
[html]  view plain  copy
  1. class ColorPoint extends Point {}  
上面代码定义了一个 ColorPoint 类,该类通过 extends 关键字,继承了 Point 类的所有属性和方法。但是由于没有部署任何代码,所以这两个类完全一样,等于复制了一个 Point 类。下面,我们在 ColorPoint 内部加上代码。
[html]  view plain  copy
  1. class ColorPoint extends Point {  
  2.   constructor(x, y, color) {  
  3.     super(x, y); // 调用父类的constructor(x, y)  
  4.     this.color = color;  
  5.   }  
  6.   
  7.   toString() {  
  8.     return this.color + ' ' + super.toString(); // 调用父类的toString()  
  9.   }  
  10. }  

上面代码中,constructor方法和toString方法之中,都出现了super关键字,它在这里表示父类的构造函数,用来新建父类的this对象。

子类必须在constructor方法中调用super方法,否则新建实例时会报错。这是因为子类没有自己的this对象,而是继承父类的this对象,然后对其进行加工。如果不调用super方法,子类就得不到this对象。

[html]  view plain  copy
  1. class Point { /* ... */ }  
  2.   
  3. class ColorPoint extends Point {  
  4.   constructor() {  
  5.   }  
  6. }  
  7.   
  8. let cp = new ColorPoint(); // ReferenceError  

上面代码中,ColorPoint继承了父类Point,但是它的构造函数没有调用super方法,导致新建实例时报错。

ES5的继承,实质是先创造子类的实例对象this,然后再将父类的方法添加到this上面(Parent.apply(this))。ES6的继承机制完全不同,实质是先创造父类的实例对象this(所以必须先调用super方法),然后再用子类的构造函数修改this

如果子类没有定义constructor方法,这个方法会被默认添加,代码如下。也就是说,不管有没有显式定义,任何一个子类都有constructor方法。

[html]  view plain  copy
  1. constructor(...args) {  
  2.   super(...args);  
  3. }  

另一个需要注意的地方是,在子类的构造函数中,只有调用super之后,才可以使用this关键字,否则会报错。这是因为子类实例的构建,是基于对父类实例加工,只有super方法才能返回父类实例。

[html]  view plain  copy
  1. class Point {  
  2.   constructor(x, y) {  
  3.     this.x = x;  
  4.     this.y = y;  
  5.   }  
  6. }  
  7.   
  8. class ColorPoint extends Point {  
  9.   constructor(x, y, color) {  
  10.     this.color = color; // ReferenceError  
  11.     super(x, y);  
  12.     this.color = color; // 正确  
  13.   }  
  14. }  

上面代码中,子类的constructor方法没有调用super之前,就使用this关键字,结果报错,而放在super方法之后就是正确的。

下面是生成子类实例的代码。

[html]  view plain  copy
  1. let cp = new ColorPoint(25, 8, 'green');  
  2.   
  3. cp instanceof ColorPoint // true  
  4. cp instanceof Point // true  

上面代码中,实例对象cp同时是ColorPointPoint两个类的实例,这与ES5的行为完全一致。


类的prototype属性和_proto_属性

大多数浏览器的ES5实现之中,每一个对象都有__proto__属性,指向对应的构造函数的prototype属性。Class作为构造函数的语法糖,同时有prototype属性和__proto__属性,因此同时存在两条继承链。

(1)子类的__proto__属性,表示构造函数的继承,总是指向父类。

(2)子类prototype属性的__proto__属性,表示方法的继承,总是指向父类的prototype属性。

[html]  view plain  copy
  1. class A {  
  2. }  
  3.   
  4. class B extends A {  
  5. }  
  6.   
  7. B.__proto__ === A // true  
  8. B.prototype.__proto__ === A.prototype // true  

上面代码中,子类B__proto__属性指向父类A,子类Bprototype属性的__proto__属性指向父类Aprototype属性。

这样的结果是因为,类的继承是按照下面的模式实现的。

[html]  view plain  copy
  1. class A {  
  2. }  
  3.   
  4. class B {  
  5. }  
  6.   
  7. // B的实例继承A的实例  
  8. Object.setPrototypeOf(B.prototype, A.prototype);  
  9.   
  10. // B继承A的静态属性  
  11. Object.setPrototypeOf(B, A);  

《对象的扩展》一章给出过Object.setPrototypeOf方法的实现。

[html]  view plain  copy
  1. Object.setPrototypeOf = function (obj, proto) {  
  2.   obj.__proto__ = proto;  
  3.   return obj;  
  4. }  

因此,就得到了上面的结果。

[html]  view plain  copy
  1. Object.setPrototypeOf(B.prototype, A.prototype);  
  2. // 等同于  
  3. B.prototype.__proto__ = A.prototype;  
  4.   
  5. Object.setPrototypeOf(B, A);  
  6. // 等同于  
  7. B.__proto__ = A;  
这两条继承链,可以这样理解:作为一个对象,子类(B)的原型(__proto__属性)是父类(A);作为一个构造函数,子类(B)的原型(prototype属性)是父类的实例。
[html]  view plain  copy
  1. Object.create(A.prototype);  
  2. // 等同于  
  3. B.prototype.__proto__ = A.prototype;  

Extends的继承目标

extends关键字后面可以跟多种类型的值。

[html]  view plain  copy
  1. class B extends A {  
  2. }  

上面代码的A,只要是一个有prototype属性的函数,就能被B继承。由于函数都有prototype属性(除了Function.prototype函数),因此A可以是任意函数。

下面,讨论三种特殊情况。

第一种特殊情况,子类继承Object类。

[html]  view plain  copy
  1. class A extends Object {  
  2. }  
  3.   
  4. A.__proto__ === Object // true  
  5. A.prototype.__proto__ === Object.prototype // true  

这种情况下,A其实就是构造函数Object的复制,A的实例就是Object的实例。

第二种特殊情况,不存在任何继承。

[html]  view plain  copy
  1. class A {  
  2. }  
  3.   
  4. A.__proto__ === Function.prototype // true  
  5. A.prototype.__proto__ === Object.prototype // true  

这种情况下,A作为一个基类(即不存在任何继承),就是一个普通函数,所以直接继承Funciton.prototype。但是,A调用后返回一个空对象(即Object实例),所以A.prototype.__proto__指向构造函数(Object)的prototype属性。

第三种特殊情况,子类继承null

[html]  view plain  copy
  1. class A extends null {  
  2. }  
  3.   
  4. A.__proto__ === Function.prototype // true  
  5. A.prototype.__proto__ === undefined // true  
这种情况与第二种情况非常像。 A 也是一个普通函数,所以直接继承 Funciton.prototype 。但是,A调用后返回的对象不继承任何方法,所以它的 __proto__ 指向 Function.prototype ,即实质上执行了下面的代码。
[html]  view plain  copy
  1. class C extends null {  
  2.   constructor() { return Object.create(null); }  
  3. }  


super关键字

super这个关键字,有两种用法,含义不同。

(1)作为函数调用时(即super(...args)),super代表父类的构造函数。

(2)作为对象调用时(即super.propsuper.method()),super代表父类。注意,此时super即可以引用父类实例的属性和方法,也可以引用父类的静态方法。

[html]  view plain  copy
  1. class B extends A {  
  2.   get m() {  
  3.     return this._p * super._p;  
  4.   }  
  5.   set m() {  
  6.     throw new Error('该属性只读');  
  7.   }  
  8. }  

上面代码中,子类通过super关键字,调用父类实例的_p属性。

由于,对象总是继承其他对象的,所以可以在任意一个对象中,使用super关键字。

[html]  view plain  copy
  1. var obj = {  
  2.   toString() {  
  3.     return "MyObject: " + super.toString();  
  4.   }  
  5. };  
  6.   
  7. obj.toString(); // MyObject: [object Object]  

实例的_proto_属性
子类实例的__proto__属性的__proto__属性,指向父类实例的__proto__属性。也就是说,子类的原型的原型,是父类的原型。
[html]  view plain  copy
  1. var p1 = new Point(2, 3);  
  2. var p2 = new ColorPoint(2, 3, 'red');  
  3.   
  4. p2.__proto__ === p1.__proto__ // false  
  5. p2.__proto__.__proto__ === p1.__proto__ // true  

上面代码中,ColorPoint继承了Point,导致前者原型的原型是后者的原型。

因此,通过子类实例的__proto__.__proto__属性,可以修改父类实例的行为。

[html]  view plain  copy
  1. p2.__proto__.__proto__.printName = function () {  
  2.   console.log('Ha');  
  3. };  
  4.   
  5. p1.printName() // "Ha"  
上面代码在ColorPoint的实例p2上向Point类添加方法,结果影响到了Point的实例p1

3、原生构造函数的继承

原生构造函数是指语言内置的构造函数,通常用来生成数据结构。ECMAScript的原生构造函数大致有下面这些。
  • Boolean()
  • Number()
  • String()
  • Array()
  • Date()
  • Function()
  • RegExp()
  • Error()
  • Object()

以前,这些原生构造函数是无法继承的,比如,不能自己定义一个Array的子类。

[html]  view plain  copy
  1. function MyArray() {  
  2.   Array.apply(this, arguments);  
  3. }  
  4.   
  5. MyArray.prototype = Object.create(Array.prototype, {  
  6.   constructor: {  
  7.     value: MyArray,  
  8.     writable: true,  
  9.     configurable: true,  
  10.     enumerable: true  
  11.   }  
  12. });  
上面代码定义了一个继承Array的 MyArray 类。但是,这个类的行为与 Array 完全不一致。
[html]  view plain  copy
  1. var colors = new MyArray();  
  2. colors[0] = "red";  
  3. colors.length  // 0  
  4.   
  5. colors.length = 0;  
  6. colors[0]  // "red"  

之所以会发生这种情况,是因为子类无法获得原生构造函数的内部属性,通过Array.apply()或者分配给原型对象都不行。原生构造函数会忽略apply方法传入的this,也就是说,原生构造函数的this无法绑定,导致拿不到内部属性。

ES5是先新建子类的实例对象this,再将父类的属性添加到子类上,由于父类的内部属性无法获取,导致无法继承原生的构造函数。比如,Array构造函数有一个内部属性[[DefineOwnProperty]],用来定义新属性时,更新length属性,这个内部属性无法在子类获取,导致子类的length属性行为不正常。

下面的例子中,我们想让一个普通对象继承Error对象。

[html]  view plain  copy
  1. var e = {};  
  2.   
  3. Object.getOwnPropertyNames(Error.call(e))  
  4. // [ 'stack' ]  
  5.   
  6. Object.getOwnPropertyNames(e)  
  7. // []  

上面代码中,我们想通过Error.call(e)这种写法,让普通对象e具有Error对象的实例属性。但是,Error.call()完全忽略传入的第一个参数,而是返回一个新对象,e本身没有任何变化。这证明了Error.call(e)这种写法,无法继承原生构造函数。

ES6允许继承原生构造函数定义子类,因为ES6是先新建父类的实例对象this,然后再用子类的构造函数修饰this,使得父类的所有行为都可以继承。下面是一个继承Array的例子。

[html]  view plain  copy
  1. class MyArray extends Array {  
  2.   constructor(...args) {  
  3.     super(...args);  
  4.   }  
  5. }  
  6.   
  7. var arr = new MyArray();  
  8. arr[0] = 12;  
  9. arr.length // 1  
  10.   
  11. arr.length = 0;  
  12. arr[0] // undefined  

上面代码定义了一个MyArray类,继承了Array构造函数,因此就可以从MyArray生成数组的实例。这意味着,ES6可以自定义原生数据结构(比如Array、String等)的子类,这是ES5无法做到的。

上面这个例子也说明,extends关键字不仅可以用来继承类,还可以用来继承原生的构造函数。因此可以在原生数据结构的基础上,定义自己的数据结构。下面就是定义了一个带版本功能的数组。

[html]  view plain  copy
  1. class VersionedArray extends Array {  
  2.   constructor() {  
  3.     super();  
  4.     this.history = [[]];  
  5.   }  
  6.   commit() {  
  7.     this.history.push(this.slice());  
  8.   }  
  9.   revert() {  
  10.     this.splice(0, this.length, ...this.history[this.history.length - 1]);  
  11.   }  
  12. }  
  13.   
  14. var x = new VersionedArray();  
  15.   
  16. x.push(1);  
  17. x.push(2);  
  18. x // [1, 2]  
  19. x.history // [[]]  
  20.   
  21. x.commit();  
  22. x.history // [[], [1, 2]]  
  23. x.push(3);  
  24. x // [1, 2, 3]  
  25.   
  26. x.revert();  
  27. x // [1, 2]  

上面代码中,VersionedArray结构会通过commit方法,将自己的当前状态存入history属性,然后通过revert方法,可以撤销当前版本,回到上一个版本。除此之外,VersionedArray依然是一个数组,所有原生的数组方法都可以在它上面调用。

下面是一个自定义Error子类的例子。

[html]  view plain  copy
  1. class ExtendableError extends Error {  
  2.   constructor(message) {  
  3.     super();  
  4.     this.message = message;  
  5.     this.stack = (new Error()).stack;  
  6.     this.name = this.constructor.name;  
  7.   }  
  8. }  
  9.   
  10. class MyError extends ExtendableError {  
  11.   constructor(m) {  
  12.     super(m);  
  13.   }  
  14. }  
  15.   
  16. var myerror = new MyError('ll');  
  17. myerror.message // "ll"  
  18. myerror instanceof Error // true  
  19. myerror.name // "MyError"  
  20. myerror.stack  
  21. // Error  
  22. //     at MyError.ExtendableError  
  23. //     ...  

注意,继承Object的子类,有一个行为差异

[html]  view plain  copy
  1. class NewObj extends Object{  
  2.   constructor(){  
  3.     super(...arguments);  
  4.   }  
  5. }  
  6. var o = new NewObj({attr: true});  
  7. console.log(o.attr === true);  // false  
上面代码中, NewObj 继承了 Object ,但是无法通过 super 方法向父类 Object 传参。这是因为ES6改变了 Object 构造函数的行为,一旦发现 Object 方法不是通过 new Object() 这种形式调用,ES6规定 Object 构造函数会忽略参数。

4、Class的取值函数(getter)和存值函数(setter)
与ES5一样,在Class内部可以使用 get set 关键字,对某个属性设置存值函数和取值函数,拦截该属性的存取行为。
[html]  view plain  copy
  1. class MyClass {  
  2.   constructor() {  
  3.     // ...  
  4.   }  
  5.   get prop() {  
  6.     return 'getter';  
  7.   }  
  8.   set prop(value) {  
  9.     console.log('setter: '+value);  
  10.   }  
  11. }  
  12.   
  13. let inst = new MyClass();  
  14.   
  15. inst.prop = 123;  
  16. // setter: 123  
  17.   
  18. inst.prop  
  19. // 'getter'  

上面代码中,prop属性有对应的存值函数和取值函数,因此赋值和读取行为都被自定义了。

存值函数和取值函数是设置在属性的descriptor对象上的。

[html]  view plain  copy
  1. class CustomHTMLElement {  
  2.   constructor(element) {  
  3.     this.element = element;  
  4.   }  
  5.   
  6.   get html() {  
  7.     return this.element.innerHTML;  
  8.   }  
  9.   
  10.   set html(value) {  
  11.     this.element.innerHTML = value;  
  12.   }  
  13. }  
  14.   
  15. var descriptor = Object.getOwnPropertyDescriptor(  
  16.   CustomHTMLElement.prototype, "html");  
  17. "get" in descriptor  // true  
  18. "set" in descriptor  // true  
上面代码中,存值函数和取值函数是定义在 html 属性的描述对象上面,这与ES5完全一致。

5、Class的Generator方法

如果某个方法之前加上星号(*),就表示该方法是一个Generator函数。

[html]  view plain  copy
  1. class Foo {  
  2.   constructor(...args) {  
  3.     this.args = args;  
  4.   }  
  5.   * [Symbol.iterator]() {  
  6.     for (let arg of this.args) {  
  7.       yield arg;  
  8.     }  
  9.   }  
  10. }  
  11.   
  12. for (let x of new Foo('hello', 'world')) {  
  13.   console.log(x);  
  14. }  
  15. // hello  
  16. // world  
上面代码中,Foo类的Symbol.iterator方法前有一个星号,表示该方法是一个Generator函数。Symbol.iterator方法返回一个Foo类的默认遍历器,for...of循环会自动调用这个遍历器。

6、Class的静态方法

类相当于实例的原型,所有在类中定义的方法,都会被实例继承。如果在一个方法前,加上static关键字,就表示该方法不会被实例继承,而是直接通过类来调用,这就称为“静态方法”。

[html]  view plain  copy
  1. class Foo {  
  2.   static classMethod() {  
  3.     return 'hello';  
  4.   }  
  5. }  
  6.   
  7. Foo.classMethod() // 'hello'  
  8.   
  9. var foo = new Foo();  
  10. foo.classMethod()  
  11. // TypeError: foo.classMethod is not a function  

上面代码中,Foo类的classMethod方法前有static关键字,表明该方法是一个静态方法,可以直接在Foo类上调用(Foo.classMethod()),而不是在Foo类的实例上调用。如果在实例上调用静态方法,会抛出一个错误,表示不存在该方法。

父类的静态方法,可以被子类继承。

[html]  view plain  copy
  1. class Foo {  
  2.   static classMethod() {  
  3.     return 'hello';  
  4.   }  
  5. }  
  6.   
  7. class Bar extends Foo {  
  8. }  
  9.   
  10. Bar.classMethod(); // 'hello'  

上面代码中,父类Foo有一个静态方法,子类Bar可以调用这个方法。

静态方法也是可以从super对象上调用的。

[html]  view plain  copy
  1. class Foo {  
  2.   static classMethod() {  
  3.     return 'hello';  
  4.   }  
  5. }  
  6.   
  7. class Bar extends Foo {  
  8.   static classMethod() {  
  9.     return super.classMethod() + ', too';  
  10.   }  
  11. }  
  12.   
  13. Bar.classMethod();  


7、Class的静态属性和实例属性
静态属性指的是Class本身的属性,即Class.propname,而不是定义在实例对象(this)上的属性。

[html]  view plain  copy
  1. class Foo {  
  2. }  
  3.   
  4. Foo.prop = 1;  
  5. Foo.prop // 1  

上面的写法为Foo类定义了一个静态属性prop

目前,只有这种写法可行,因为ES6明确规定,Class内部只有静态方法,没有静态属性。

[html]  view plain  copy
  1. // 以下两种写法都无效  
  2. class Foo {  
  3.   // 写法一  
  4.   prop: 2  
  5.   
  6.   // 写法二  
  7.   static prop: 2  
  8. }  
  9.   
  10. Foo.prop // undefined  

ES7有一个静态属性的提案,目前Babel转码器支持。

这个提案对实例属性和静态属性,都规定了新的写法。

(1)类的实例属性

类的实例属性可以用等式,写入类的定义之中。

[html]  view plain  copy
  1. class MyClass {  
  2.   myProp = 42;  
  3.   
  4.   constructor() {  
  5.     console.log(this.myProp); // 42  
  6.   }  
  7. }  

上面代码中,myProp就是MyClass的实例属性。在MyClass的实例上,可以读取这个属性。

以前,我们定义实例属性,只能写在类的constructor方法里面。

[html]  view plain  copy
  1. class ReactCounter extends React.Component {  
  2.   constructor(props) {  
  3.     super(props);  
  4.     this.state = {  
  5.       count: 0  
  6.     };  
  7.   }  
  8. }  

上面代码中,构造方法constructor里面,定义了this.state属性。

有了新的写法以后,可以不在constructor方法里面定义。

[html]  view plain  copy
  1. class ReactCounter extends React.Component {  
  2.   state = {  
  3.     count: 0  
  4.   };  
  5. }  

这种写法比以前更清晰。

为了可读性的目的,对于那些在constructor里面已经定义的实例属性,新写法允许直接列出。

[html]  view plain  copy
  1. class ReactCounter extends React.Component {  
  2.   constructor(props) {  
  3.     super(props);  
  4.     this.state = {  
  5.       count: 0  
  6.     };  
  7.   }  
  8.   state;  
  9. }  

(2)类的静态属性

类的静态属性只要在上面的实例属性写法前面,加上static关键字就可以了。

[html]  view plain  copy
  1. class MyClass {  
  2.   static myStaticProp = 42;  
  3.   
  4.   constructor() {  
  5.     console.log(MyClass.myProp); // 42  
  6.   }  
  7. }  

同样的,这个新写法大大方便了静态属性的表达。

[html]  view plain  copy
  1. // 老写法  
  2. class Foo {  
  3. }  
  4. Foo.prop = 1;  
  5.   
  6. // 新写法  
  7. class Foo {  
  8.   static prop = 1;  
  9. }  

上面代码中,老写法的静态属性定义在类的外部。整个类生成以后,再生成静态属性。这样让人很容易忽略这个静态属性,也不符合相关代码应该放在一起的代码组织原则。另外,新写法是显式声明(declarative),而不是赋值处理,语义更好。


8、new.target属性

new是从构造函数生成实例的命令。ES6为new命令引入了一个new.target属性,(在构造函数中)返回new命令作用于的那个构造函数。如果构造函数不是通过new命令调用的,new.target会返回undefined,因此这个属性可以用来确定构造函数是怎么调用的。

[html]  view plain  copy
  1. function Person(name) {  
  2.   if (new.target !== undefined) {  
  3.     this.name = name;  
  4.   } else {  
  5.     throw new Error('必须使用new生成实例');  
  6.   }  
  7. }  
  8.   
  9. // 另一种写法  
  10. function Person(name) {  
  11.   if (new.target === Person) {  
  12.     this.name = name;  
  13.   } else {  
  14.     throw new Error('必须使用new生成实例');  
  15.   }  
  16. }  
  17.   
  18. var person = new Person('张三'); // 正确  
  19. var notAPerson = Person.call(person, '张三');  // 报错  

上面代码确保构造函数只能通过new命令调用。

Class内部调用new.target,返回当前Class。

[html]  view plain  copy
  1. class Rectangle {  
  2.   constructor(length, width) {  
  3.     console.log(new.target === Rectangle);  
  4.     this.length = length;  
  5.     this.width = width;  
  6.   }  
  7. }  
  8.   
  9. var obj = new Rectangle(3, 4); // 输出 true  

需要注意的是,子类继承父类时,new.target会返回子类。

[html]  view plain  copy
  1. class Rectangle {  
  2.   constructor(length, width) {  
  3.     console.log(new.target === Rectangle);  
  4.     // ...  
  5.   }  
  6. }  
  7.   
  8. class Square extends Rectangle {  
  9.   constructor(length) {  
  10.     super(length, length);  
  11.   }  
  12. }  
  13.   
  14. var obj = new Square(3); // 输出 false  

上面代码中,new.target会返回子类。

利用这个特点,可以写出不能独立使用、必须继承后才能使用的类。


9、Mixin模式的实现
Mixin模式指的是,将多个类的接口“混入”(mix in)另一个类。它在ES6的实现如下。
[html]  view plain  copy
  1. function mix(...mixins) {  
  2.   class Mix {}  
  3.   
  4.   for (let mixin of mixins) {  
  5.     copyProperties(Mix, mixin);  
  6.     copyProperties(Mix.prototype, mixin.prototype);  
  7.   }  
  8.   
  9.   return Mix;  
  10. }  
  11.   
  12. function copyProperties(target, source) {  
  13.   for (let key of Reflect.ownKeys(source)) {  
  14.     if ( key !== "constructor"  
  15.       && key !== "prototype"  
  16.       && key !== "name"  
  17.     ) {  
  18.       let desc = Object.getOwnPropertyDescriptor(source, key);  
  19.       Object.defineProperty(target, key, desc);  
  20.     }  
  21.   }  
  22. }  

上面代码的mix函数,可以将多个对象合成为一个类。使用的时候,只要继承这个类即可。

[html]  view plain  copy
  1. class DistributedEdit extends mix(Loggable, Serializable) {  
  2.   // ...  
  3. }  
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值