Meaning of prototype in javascript

前端 未结 6 979
别跟我提以往
别跟我提以往 2021-02-02 12:10

I wrote short code of inheritance of reader from Person:



        
6条回答
  •  -上瘾入骨i
    2021-02-02 12:49

    When you put the method in the constructor and create an object out of that constructor, each object carries it's own getName function. For 10 Person instances, each carries it's own getName, therefore 10 separate getName functions.

    If you place getName in the prototype of the constructor, that same getName function is shared/inherited across all instances. so for 10 instances of Person, each has getName but refer only to 1 getName function.

    Using prototypes saves memory since the method is shared across instances so only one is used.

提交回复
热议问题