|
正在研究,贴一个自己写的例子:
- class ParameterTypeError extends Error {
- constructor(paramName, paramType) {
- if (!(typeof paramName == 'string'))
- throw new ParameterTypeError('paramName', String);
- if (!(paramType instanceof Function))
- throw new ParameterTypeError('paramType', Function);
-
- let msg = 'Parameter "' + paramName +
- '" must be a ' + paramType.name +
- ' object.';
- super(msg);
-
- this.ParameterName = paramName;
- this.ParameterType = paramType;
- }
-
- toString() {
- return ParameterTypeError.name + ' : ' + this.message;
- }
-
- static check(param, paramName, paramType) {
- if (!((param instanceof paramType) ||
- (typeof param == paramType.name.toLowerCase())))
- throw new ParameterTypeError(paramName, paramType);
- }
- }
- class Point {
- constructor(x, y) {
- ParameterTypeError.check(x, 'x', Number);
- ParameterTypeError.check(y, 'y', Number);
-
- this.x = x;
- this.y = y;
-
- if (Point._count == undefined) {
- Point._count = 1;
- } else {
- Point._count++;
- }
- }
-
- static get count() {
- if (Point._count == undefined)
- return 0;
- else
- return Point._count;
- }
-
- static get Version() {
- return '2D';
- }
-
- toString() {
- return '(' + this.x + ', ' + this.y + ')';
- }
-
- distanceTo(p) {
- ParameterTypeError.check(p, 'p', Point);
- return Math.sqrt(
- Math.pow(this.x - p.x, 2) +
- Math.pow(this.y - p.y, 2));
- }
-
- static distanceBetween(p1, p2) {
- ParameterTypeError.check(p1, 'p1', Point);
- ParameterTypeError.check(p2, 'p2', Point);
-
- return Math.sqrt(
- Math.pow(p1.x - p2.x, 2) +
- Math.pow(p1.y - p2.y, 2));
- }
- }
- class NamedPoint extends Point {
- constructor(name, x, y) {
- ParameterTypeError.check(name, 'name', String);
-
- super(x, y);
- this._name = name;
- }
-
- get name() {
- return this._name;
- }
-
- toString() {
- return this._name + super.toString();
- }
- }
-
- function classTest() {
- let p = new Point(3, 4);
- Console.log(p);
- let np = new NamedPoint("ShotTarget", 6, 8);
- Console.log(np);
- //为只读属性赋值是无效的,但也不报错
- np.name = "WTF";
- Console.log(np);
- Console.log(np.name);
- Console.log(p.distanceTo(np));
- Console.log('instance count : ' + Point.count);
- //静态方法会被子类继承
- Console.log(NamedPoint.distanceBetween(np, p));
- //实例方法会被子类继承
- Console.log(np.distanceTo(p));
- //静态属性
- Console.log('static property Version : ' + Point.Version);
- //自定义异常
- try {
- p.distanceTo(33);
- } catch(e) {
- Console.log(e.message);
- Console.log(e);
- }
- Console.log(JSON.stringify(np));
- }
复制代码 |
|