[removed] Overwriting function's prototype - bad practice?

后端 未结 6 535
天涯浪人
天涯浪人 2020-12-13 00:51

Since when we declare a function we get its prototype\'s constructor property point to the function itself, is it a bad practice to overwrite function\'s prototype like so:<

6条回答
  •  执笔经年
    2020-12-13 01:33

    It's not bad practice but you have to know what you are doing and why. It is very useful for prototypal inheritance. The object of which you overwrite the prototype will get all the properties of the object you assign to it's prototype:

    You cause an object to inherit using

    ChildClassName.prototype = new ParentClass();.
    

    Now ChildClassName has all functionality of ParentClass but loses any functionality that was assigned to it's prototype before. You need to remember to reset the constructor property for the object using

    ChildClassName.prototype.constructor=ChildClassName. 
    

    Otherwise the object will be reported to be (when testing for the type of an object) of the ParentClass type instead of the ChildClassName type.

    And now you can add more methods to the ChildClassName object in the way you described yourself.

    ChildClassName.prototype.myMethod = function(){
        //do stuff
    }
    

    The result being a parent object/'class'(there are no real classes in javascript of course) and a child object/'class' that inherits from it and extends its functionality.

    You just have to know that if you overwrite the prototype, any properties that where assigned to it will be gone. When constructing inheriting objects this might be exactly what you want.

提交回复
热议问题