Which way is best for creating an object in JavaScript? Is `var` necessary before an object property?

前端 未结 8 1880
无人共我
无人共我 2020-11-27 08:59

So far I saw three ways for creating an object in JavaScript. Which way is best for creating an object and why?

I also saw that in all of these examples the keyword

8条回答
  •  佛祖请我去吃肉
    2020-11-27 09:19

    I guess it depends on what you want. For simple objects, I guess you could use the second methods. When your objects grow larger and you're planning on using similar objects, I guess the first method would be better. That way you can also extend it using prototypes.

    Example:

    function Circle(radius) {
        this.radius = radius;
    }
    Circle.prototype.getCircumference = function() {
        return Math.PI * 2 * this.radius;
    };
    Circle.prototype.getArea = function() {
        return Math.PI * this.radius * this.radius;
    }
    

    I am not a big fan of the third method, but it's really useful for dynamically editing properties, for example var foo='bar'; var bar = someObject[foo];.

提交回复
热议问题