javascript JS-ES6-ES2015类,cheatsnippet.js

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了javascript JS-ES6-ES2015类,cheatsnippet.js相关的知识,希望对你有一定的参考价值。

// based on parts of: http://exploringjs.com/es6/ch_classes.html

const methodName = 'myMethod'; // for computed method names

// class
class Point {
  constructor(x, y) {
    this.x = x;
    this.y = y;
    this._privateProperty = 0; // though it's a naming convention only
  }
  ; // OK, ignored; other delimiters forbidden
  toString() { // prototypical method
    return `(${this.x}, ${this.y})`;
  }
  static staticMethod() { // static; inheritable
    return 'classy';
  }
  static get ZERO() { // static getter; see also approach of assigning static property below
    return new Point(0, 0);
  }

  // getter & setters; used as obj.prop
  get prop() { return 'getter'; }
  set prop(value) { }

  // computed method names
  ['my'+'Method']() {}
  [methodName]() {} // see const above class def

  // private data: http://exploringjs.com/es6/ch_classes.html#sec_private-data-for-classes
  // 1. scoping
  // 2. naming convention
  // 3. WeakMap
  // 4. Symbol

  // other
  logStaticProp() {
    Point.ZERO(); // employ inner name
  }
}
Point.ZERO = new Point(0,0); // static property

// Read-only property
// See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/defineProperty
// (what about class level static?)
obj = Object.defineProperty(obj, prop, descriptor); // descriptor - as per link above

// subclass
class ColorPoint extends Point {
  constructor(x, y, color) {
    super(x,y); // call super() and call it before using `this`
    this.color = color;
  }
  /*
    Default constructor for derived class:
      constructor(...args) {
        super(...args);
      }
  */
  toString() {
    return super.toString() + ' in ' + this.color;
  }
  static staticMethod() { // extend/replace static methods
    super.staticMethod();
  }
}

// see more classes after next section

// usage
// you cannot call fn that uses class before class defined
const cp = new ColorPoint(25, 8, 'green');
cp.toString();
cp instanceof ColorPoint;   // true
cp instanceof Point;        // true
Object.getPrototypeOf(ColorPoint) == Point; // true
typeof Point;               // 'function'
Point();                    // ERROR! TypeError: Classes can’t be function-called
Point.staticMethod();


// anonymous class expression
const myClassA = class {
  // ...
};
const instA = new MyClassA();

// named class where class name is visible only inside it
const myClassB = class Me {
  getClassName() {
    return Me.name;
  }
};
const instB = new MyClassB();
inst.getClassName(); // Me
Me.name; // ReferenceError: Me is not defined

// special methods
class IterableArguments {
  constructor (...args) {
    this.args = args;
  }
  // make class iterable (via for-of loops etc)
  [Symbol.iterator]() {
  }

  // generator
  * [Symbol.iterator]() {
    for (const arg of this.args) {
      yield arg;
    }
  }
}
// usage
for (const x of new IterableArguments('hello','world')) {
  console.log(x);
}

// special extensions - Exception Class
class MyError extends Error {
}
throw new MyError('Smth happened!');

// special arrays
// Note that subclassing Array is usually not the best solution.
// It’s often better to create your own class (whose interface you control)
// and to delegate to an Array in a private property.
class Stack extends Array {
  get top() {
    return this[this.length - 1];
  }
}
var stack = new Stack();
stack.push(1);
stack.push(2);
stack.top; // 2
stack.length; // 2

// Multiple inheritance
class Person {}
class Storage { save(db){} }
class Validation { validate(schema){} }
class Employee extends Storage, Validation, Person { } // Error!

class Person {}
const Storage = Sup => class extends Sup {
  save(database) { }
};
const Validation = Sup => class extends Sup {
  validate(schema) { }
};
class Employee extends Storage(Validation(Person)) {
}

// Function.prototype.apply() ===
function instantiate(TheClass, args) {
  return new TheClass(...args);
}
// or
function instantiate(TheClass, args) {
  return Reflect.construct(TheClass, args);
}

/* =================================== further reading ===============
   http://exploringjs.com/es6/ch_classes.html#sec_private-data-for-classes
   https://github.com/rwaldron/tc39-notes/blob/master/es6/2015-01/jan2015-allen-slides.pdf
 */

以上是关于javascript JS-ES6-ES2015类,cheatsnippet.js的主要内容,如果未能解决你的问题,请参考以下文章

js-ES6学习笔记-Class

js-ES6学习笔记-Class

js-ES6学习笔记-Generator函数的异步应用

js-ES6学习笔记-Class

js-ES6学习笔记-编程风格

ES6 - ECMAScript 6.0(ES2015)