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
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章