Meaning of prototype in javascript

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

I wrote short code of inheritance of reader from Person:



        
6条回答
  •  眼角桃花
    2021-02-02 12:46

    The difference is that when you put it on the prototype, all instances of Person share the same code for getName -- you can change getName on all instances of Person by assigning something else:

    Person.prototype.getName = function() { return 'Mr Jones' };
    

    Also, since they share the same code, it's less memory intensive: You only have one copy of the getName function, instead of one copy per instance.

    Another difference is that you can later set the Person as the prototype of another class, let's say Man, and it will inherit the properties/methods.

    Update: Here is a good post explaining other properties of prototypes: https://stackoverflow.com/a/1534286/295262

提交回复
热议问题