How to “properly” create a custom object in JavaScript?

后端 未结 15 1980
被撕碎了的回忆
被撕碎了的回忆 2020-11-21 08:07

I wonder about what the best way is to create an JavaScript object that has properties and methods.

I have seen examples where the person used var self = this<

15条回答
  •  心在旅途
    2020-11-21 08:33

    To continue off of bobince's answer

    In es6 you can now actually create a class

    So now you can do:

    class Shape {
        constructor(x, y) {
            this.x = x;
            this.y = y;
        }
    
        toString() {
            return `Shape at ${this.x}, ${this.y}`;
        }
    }
    

    So extend to a circle (as in the other answer) you can do:

    class Circle extends Shape {
        constructor(x, y, r) {
            super(x, y);
            this.r = r;
        }
    
        toString() {
            let shapeString = super.toString();
            return `Circular ${shapeString} with radius ${this.r}`;
        }
    }
    

    Ends up a bit cleaner in es6 and a little easier to read.


    Here is a good example of it in action:

    class Shape {
      constructor(x, y) {
        this.x = x;
        this.y = y;
      }
    
      toString() {
        return `Shape at ${this.x}, ${this.y}`;
      }
    }
    
    class Circle extends Shape {
      constructor(x, y, r) {
        super(x, y);
        this.r = r;
      }
    
      toString() {
        let shapeString = super.toString();
        return `Circular ${shapeString} with radius ${this.r}`;
      }
    }
    
    let c = new Circle(1, 2, 4);
    
    console.log('' + c, c);

提交回复
热议问题