Why use chained prototype inheritance in javascript?

后端 未结 3 1104
礼貌的吻别
礼貌的吻别 2021-02-08 10:05

perf

Why do we build a prototype inheritance chain rather then using object composition. Looking up through the prototype for each step in the chain get\'s expensive.

3条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-02-08 10:26

    Here are some benefits I can think of in order of importance

    Memory usage

    By using the prototype, you create shared properties. Your approach copies all the values to each object.

    Upfront cost of setting up objects

    Thought you are saving a little bit of time later, you are incurring the cost of copying properties when you set up the object. It'd be nice for you to account for that in your performance tests. This is a benefit that may be outweighed if you read a lot more than you set up your objects.

    instanceOf

    Good code doesn't use instanceOf, but sometimes you can't make all your code perfect, so why break a language feature?

    Dynamically changing the prototype

    Most people will claim that they never need this (like me), but many of us have extended Array.prototype after instantiating some arrays (not that you should do it). With the copy properties approach you lose the reference to the original object.

    Unashamed plug: http://js-bits.blogspot.com/2010/08/javascript-inheritance-done-right.html

    Last Note If you this is actually a bottleneck in an app, I would not be reluctant to use it for the objects in question

提交回复
热议问题