Is there a difference in using a constructor to create an object versus returning an object?

前端 未结 3 360
醉梦人生
醉梦人生 2021-01-20 03:27

Is there any difference in how these functions operate? The first one is more typically of what I think about when thinking of a constructor.

Example 1: using t

3条回答
  •  悲&欢浪女
    2021-01-20 03:39

    The difference is the constructor used to create the object returned.

    new Book('A Good Book', '500 pages');
    

    creates a Book object instance, with the instance inheriting properties from Book.prototype, including a constructor property value of Book. The Book.prototype object itself inherits from Object.prototype.

    var other = Movie('Gladiator', '180');
    

    uses Movie as a factory function (new not required) and returns an Object object instance, with the instance inheriting properties directly fromObject.prototype, including a constructor property value of Object.

    More briefly stated, Object literal syntax creates an Object object.

提交回复
热议问题