Understanding the difference between Object.create() and new SomeFunction()

后端 未结 11 2611
失恋的感觉
失恋的感觉 2020-11-22 05:05

I recently stumbled upon the Object.create() method in JavaScript, and am trying to deduce how it is different from creating a new instance of an object with

11条回答
  •  时光取名叫无心
    2020-11-22 05:55

    The difference is the so-called "pseudoclassical vs. prototypal inheritance". The suggestion is to use only one type in your code, not mixing the two.

    In pseudoclassical inheritance (with "new" operator), imagine that you first define a pseudo-class, and then create objects from that class. For example, define a pseudo-class "Person", and then create "Alice" and "Bob" from "Person".

    In prototypal inheritance (using Object.create), you directly create a specific person "Alice", and then create another person "Bob" using "Alice" as a prototype. There is no "class" here; all are objects.

    Internally, JavaScript uses "prototypal inheritance"; the "pseudoclassical" way is just some sugar.

    See this link for a comparison of the two ways.

提交回复
热议问题