ES6学习12(Class)

来源:互联网 发布:免费阅读软件下载 编辑:程序博客网 时间:2024/05/23 20:07

Class基本语法

概述

ES5的传统方法:

function Point(x, y) {  this.x = x;  this.y = y;}Point.prototype.toString = function () {  return '(' + this.x + ', ' + this.y + ')';};var p = new Point(1, 2);

ES6中:

//定义类class Point {  constructor(x, y) {    this.x = x;    this.y = y;  }  toString() {    return '(' + this.x + ', ' + this.y + ')';  }}console.log(typeof Point) // "function"console.log(Point === Point.prototype.constructor) // true//由此可见其实ES6的class就是换了一种定义对象的写法,本质上的实现和使用还是和ES5相同的var a = new Point(10,20);

构造函数的prototype属性,在ES6的“类”上面继续存在。事实上,类的所有方法都定义在类的prototype属性上面。

//类的方法都定义在prototype对象上面console.log(a.toString());//(10, 20)console.log(Point.prototype.toString.call(a));//(10, 20)//由于类的方法都定义在prototype对象上面//所以类的新方法可以添加在prototype对象上面//Object.assign方法可以很方便地一次向类添加多个方法。Object.assign(Point.prototype, {    moveLeft(step){        this.x -= step;    },    moveRight(step){        this.x += step;    }});a.moveLeft(1);console.log(a.toString());//(9, 20)

constructor方法

constructor方法是类的默认方法,通过new命令生成对象实例时,自动调用该方法。一个类必须有constructor方法,如果没有显式定义,一个空的constructor方法会被默认添加。
constructor方法默认返回实例对象(即this),完全可以指定返回另外一个对象。

class Foo {  constructor() {    return Object.create(null);  }}console.log(new Foo() instanceof Foo);// false

不存在变量提升

new Foo(); // ReferenceErrorclass Foo {}

Class表达式

需要注意的是,这个类的名字是MyClass而不是Me,Me只在Class的内部代码可用,指代当前类。

//如果使用表达式的话,类名是变量名而不是class后面的名字const MyClass = class Me {  getClassName() {    return Me.name;  }};let inst = new MyClass();inst.getClassName() // MeMe.name // ReferenceError: Me is not defined

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

//使用表达式可以写出立即实例化的匿名类let person = new class {  constructor(name) {    this.name = name;  }  sayName() {    console.log(this.name);  }}('张三');person.sayName(); // "张三"

私有方法

私有方法是常见需求,但ES6不提供,只能通过变通方法模拟实现。
你可以通过命名方法加以识别,私有方法上加一个下划线,但是这并不起什么实质性的作用。
还有一种方法就是利用Symbol:

const bar = Symbol('bar');const snaf = Symbol('snaf');export default class myClass{  // 公有方法  foo(baz) {    this[bar](baz);  }  // 私有方法  [bar](baz) {    return this[snaf] = baz;  }};

严格模式

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

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

Class的继承

Class之间可以通过extends关键字实现继承,这比ES5的通过修改原型链实现继承,要清晰和方便很多。

class ColorPoint extends Point {}

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

class ColorPoint extends Point {  constructor(x, y, color) {    //子类必须在constructor方法中调用super方法,否则新建实例时会报错    //这是因为子类没有自己的this对象,而是继承父类的this对象,然后对其进行加工    //如果不调用super方法,子类就得不到this对象    super(x, y); // 调用父类的constructor(x, y)    //只有调用super之后,才可以使用this关键字,否则会报错    this.color = color;  }  toString() {    return this.color + ' point:' + super.toString(); // 调用父类的toString()  }}let cp = new ColorPoint(25, 8, 'green');console.log(cp instanceof ColorPoint) // trueconsole.log(cp instanceof Point) // trueconsole.log(cp.toString());//green point:(25, 8)

类的prototype属性和_proto_属性

大多数浏览器的ES5实现之中,每一个对象都有_proto_属性,指向对应的构造函数的prototype属性。
在ES6中如果有两个类,一个要继承另一个,内部是这么实现的:

class A {}class B {}// B的实例继承A的实例Object.setPrototypeOf(B.prototype, A.prototype);// B继承A的静态属性Object.setPrototypeOf(B, A);//Object.setPrototypeOf的实现Object.setPrototypeOf = function (obj, proto) {  obj.__proto__ = proto;  return obj;}

Class作为构造函数的语法糖,同时有prototype属性和_proto_属性,因此同时存在两条继承链:

  • 子类的_proto_属性,表示构造函数的继承,总是指向父类。
  • 子类prototype属性的_proto_属性,表示方法的继承,总是指向父类的prototype属性。
    所以:
class A {}class B extends A {}console.log(B.__proto__ === A) // trueconsole.log(B.prototype.__proto__ === A.prototype) // true

Extends 的继承目标

extends关键字后面可以跟多种类型的值。只要是一个有prototype属性的函数,就能被继承。由于函数都有prototype属性(除了Function.prototype函数),因此被继承的可以是任意函数。
如果不存在任何继承:

class A {}A.__proto__ === Function.prototype // trueA.prototype.__proto__ === Object.prototype // true

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

class A extends null {}A.__proto__ === Function.prototype // trueA.prototype.__proto__ === undefined // true

A也是一个普通函数,所以直接继承Funciton.prototype。但是,A调用后返回的对象不继承任何方法,所以它的proto指向Function.prototype,即实质上执行了下面的代码。

class C extends null {  constructor() { return Object.create(null); }}

super

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

  • 作为函数调用时(即super(…args)),super代表父类的构造函数。
  • 作为对象调用时(即super.prop或super.method()),super代表父类。注意,此时super即可以引用父类实例的属性和方法,也可以引用父类的静态方法。

实例的proto属性

子类实例的proto属性的proto属性,指向父类实例的proto属性。也就是说,子类的原型的原型,是父类的原型。因此,通过子类实例的proto.proto属性,可以修改父类实例的行为。

var p1 = new Point(2, 3);var p2 = new ColorPoint(2, 3, 'red');//通过实例的这个属性可以访问到实例的原型console.log(p2.__proto__.toString.call(p2));//red point:(2, 3)//通过实例的原型的这个属性可以访问到父类console.log(p2.__proto__.__proto__.toString.call(p2));//(2, 3)

原生构造函数的继承

原生构造函数是指语言内置的构造函数,通常用来生成数据结构。
Boolean()
Number()
String()
Array()
Date()
Function()
RegExp()
Error()
Object()
在ES5中是先新建子类的实例对象this,再将父类的属性添加到子类上,但是子类无法获得原生构造函数的内部属性,导致无法继承原生的构造函数。比如,Array构造函数有一个内部属性[[DefineOwnProperty]],用来定义新属性时,更新length属性,这个内部属性无法在子类获取,导致子类的length属性行为不正常。

function MyArray() {  Array.apply(this, arguments);}MyArray.prototype = Object.create(Array.prototype, {  constructor: {    value: MyArray,    writable: true,    configurable: true,    enumerable: true  }});var colors = new MyArray();colors[0] = "red";console.log(colors.length)  // 0colors.length = 0;console.log(colors[0])  // "red"

而ES6中是先新建父类的实例对象this,然后再用子类的构造函数修饰this,使得父类的所有行为都可以继承。

class MyArray extends Array {  constructor(...args) {    super(...args);  }}var arr = new MyArray();arr[0] = 12;console.log(arr.length) // 1arr.length = 0;console.log(arr[0]) // undefined

所以说明,extends关键字不仅可以用来继承类,还可以用来继承原生的构造函数。因此可以在原生数据结构的基础上,定义自己的数据结构。
比如下面这个带版本控制的Array:

class VersionedArray extends Array {  constructor() {    super();    this.history = [[]];  }  commit() {    this.history.push(this.slice());  }  revert() {    this.splice(0, this.length, ...this.history[this.history.length - 1]);  }}var x = new VersionedArray();x.push(1);x.push(2);console.log(x) // [1, 2]console.log(x.history) // [[]]x.commit();console.log(x.history) // [[], [1, 2]]x.push(3);console.log(x) // [1, 2, 3]x.revert();console.log(x) // [1, 2]

在VersionedArray的实例上,除了所有的数组方法可以使用之外,还多加了版本控制的两个方法。

Class的取值函数(getter)和存值函数(setter)

与ES5一样,在Class内部可以使用get和set关键字,对某个属性设置存值函数和取值函数,拦截该属性的存取行为。

class CustomHTMLElement {  constructor(element) {    this.element = element;  }  get html() {    return this.element.innerHTML;  }  set html(value) {    this.element.innerHTML = value;  }}var logoEle = new CustomHTMLElement(document.getElementById("logo"));console.log(logoEle.html);logoEle.html = "oh no";

Class的Generator方法

这个和以前变化也不大:

class Foo {  constructor(...args) {    this.args = args;  }  * [Symbol.iterator]() {    for (let arg of this.args) {      yield arg;    }  }}for (let x of new Foo('hello', 'world')) {  console.log(x);}// hello// world

Class的静态方法

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

class Foo {  static classMethod() {    return 'hello';  }}console.log(Foo.classMethod()) // 'hello'var foo = new Foo();foo.classMethod()// TypeError: foo.classMethod is not a function

父类的静态方法,可以被子类继承。
静态方法也是可以从super对象上调用的。

Class的静态属性和实例属性

因为ES6明确规定,Class内部只有静态方法,没有静态属性。所以只能在外部定义:

class Foo {  // 报错  //prop: 2  //static prop: 2}console.log(Foo.prop) // undefinedFoo.prop = 1;console.log(Foo.prop) // 1

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

class MyClass {  static myStaticProp = 42;  myProp = 41;  constructor() {    console.log(MyClass.myStaticProp); // 42    console.log(this.myProp); // 41  }}

new.target属性

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

function Person(name) {  if (new.target === Person) {    this.name = name;  } else {    throw new Error('必须使用new生成实例');  }}var person = new Person('张三'); // 正确var notAPerson = Person.call(person, '张三');  // 报错

需要注意的是,子类继承父类时,new.target会返回子类。
利用这个特点,可以写出不能独立使用、必须继承后才能使用的类。

class Shape {  constructor() {    if (new.target === Shape) {      throw new Error('本类不能实例化');    }  }}class Rectangle extends Shape {  constructor(length, width) {    super();    this.length = length;    this.width = width;  }  to() {    console.log(this.length+'&'+this.width);  }}var y = new Rectangle(3, 4);  // 正确y.to();var x = new Shape();  // 报错

Mixin模式的实现

Mixin模式指的是,将多个类的接口“混入”(mix in)另一个类。

function mix(...mixins) {  class Mix {}  //将每个类的实例和原型中的属性拷贝到新的类里  for (let mixin of mixins) {    copyProperties(Mix, mixin);    copyProperties(Mix.prototype, mixin.prototype);  }  return Mix;}function copyProperties(target, source) {  for (let key of Reflect.ownKeys(source)) {    if ( key !== "constructor"      && key !== "prototype"      && key !== "name"    ) {      let desc = Object.getOwnPropertyDescriptor(source, key);      Object.defineProperty(target, key, desc);    }  }}//使用时class DistributedEdit extends mix(Loggable, Serializable) {  // ...}
0 0
原创粉丝点击