Should I use prototype or not?

后端 未结 3 1286
Happy的楠姐
Happy的楠姐 2020-11-29 00:47

I\'m creating a Vector class, which can basically hold three numerical values. However, a lot of operations can be done on such a vector - e.g. getting the magnitude, adding

3条回答
  •  无人及你
    2020-11-29 01:33

    ECMA 6 http://es6-features.org/#BaseClassAccess

    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()
        }
    }
    

    ECMA 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 () {
        return "Rectangle > " + Shape.prototype.toString.call(this);
    };
    var Circle = function (id, x, y, radius) {
        Shape.call(this, id, x, y);
        …
    };
    Circle.prototype.toString = function () {
        return "Circle > " + Shape.prototype.toString.call(this);
    };
    

提交回复
热议问题