ECMAScript 6(ES6) 特性概览和与ES5的比较11(下)-类

4.基类访问

直观访问基类构造函数和方法。

ECMAScript 6

class Shape {
    ...
    toString () {
        return `Shape(${this.id})`
    }
}
class Rectangle extends Shape {
    constructor (id, x, y, width, height) {
        super(id, x, y)
        ...
    }
    toString () {
        return "Rectangle > " + super.toString()
    }
}
class Circle extends Shape {
    constructor (id, x, y, radius) {
        super(id, x, y)
        ...
    }
    toString() {
        return "Circle > " + super.toString()
    }
}

ECMAScript 5

var Shape = function (id, x, y) {
    ...
};
Shape.prototype.toString = function (x, y) {
    return "Shape(" + this.id +")"
};
var Rectangle = function (id, x, y, width, height) {
    Shape.call(this, id, x, y);
    ...
}
Rectangle.prototype.toString = function () {
    Shape.call(this, id, x, y);
    ...
};
Circle.prototype.toString = function () {
    return "Circle >" + Shape.prototype.toString.call(this);
}

5.静态成员

简单支持静态类成员

ECMAScript 6

class Rectangle extends Shape {
    ...
    static defaultRectangle () {
        return new Rectangle("default", 0, 0, 100, 100)
    }
}
class Circle extends Shape {
    ...
    static defaultCircle () {
        return new Circle("default", 0, 0, 100)
    }
}
var defRectangle = Rectangle.defaultRectangle()
var defCircle = Circle.defaultCircle()

ECMAScript 5

var Rectangle = function (id, x, y, width, height) {
    …
}
Rectangle.defaultRectangle = function () {
    return new Rectangle("default", 0, 0, 100, 100)
}
var Circle = function (id, x, y, width, height) {
    …
}
Circle.defaultCircle = function () {
    return new Circle("default", 0, 0, 100)
}
var defRectangle = Rectangle.defaultRectangle()
var defCircle    = Circle.defaultCircle()

6.Getter/Setter

Getter/Setter也直接在类里面(可能是自ECMADcript5.1以来,并不只是在对象初始化器中)

ECMAScript 6

class Rectangle {
    constructor (width, height) {
        this._width  = width
        this._height = height
    }
    set width  (width)  { this._width = width               }
    get width  ()       { return this._width                }
    set height (height) { this._height = height             }
    get height ()       { return this._height               }
    get area   ()       { return this._width * this._height }
}
var r = new Rectangle(50, 20)
r.area === 1000

ECMAScript 5

var Rectangle = function (width, height) {
    this._width  = width
    this._height = height
}
Rectangle.prototype = {
    set width  (width)  { this._width = width               },
    get width  ()       { return this._width                },
    set height (height) { this._height = height             },
    get height ()       { return this._height               },
    get area   ()       { return this._width * this._height }
}
var r = new Rectangle(50, 20)
r.area === 1000

猜你喜欢

转载自blog.csdn.net/u010622874/article/details/84030412