Meaning of prototype in javascript

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

I wrote short code of inheritance of reader from Person:



        
6条回答
  •  既然无缘
    2021-02-02 12:47

    When you put something on the prototype, every instance of the object shares the same code for the method. They are all using the same function instance.

    When you simply put a method on this, every object instance has its own copy of the same method.

    Using prototype is much more efficient. Note this is why typically methods are placed on the prototype, since you typically want all instances to use the same method, but properties are placed on the instance itself, because typically you don't want all instances to share the same properties.

    For your comment, if you put a method on the constructor function of an object, then you have in effect created a "static" method. No instance of the object will have that method, they all must access it on the constructor function. So in your case, Person.someMethod().

提交回复
热议问题