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

后端 未结 6 548
天涯浪人
天涯浪人 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:27

    I can't see anyone mentioning best practice as far as this is concerned, so I think it comes down to whether you can see the constructor property ever being useful.

    One thing worth noting is that the constructor property, if you don't destroy it, will be available on the created object too. It seems to me like that could be useful:

    var ClassOne = function() {alert("created one");}
    var ClassTwo = function() {alert("created two");}
    
    ClassOne.prototype.aProperty = "hello world"; // preserve constructor
    ClassTwo.prototype = {aProperty: "hello world"}; // destroy constructor
    
    var objectOne = new ClassOne(); // alerts "created one"
    var objectTwo = new ClassTwo(); // alerts "created two"
    
    objectOne.constructor(); // alerts "created one" again
    objectTwo.constructor(); // creates and returns an empty object instance
    

    So it seems to me that it's an architectural decision. Do you want to allow a created object to re-call its constructor after it's instantiated? If so preserve it. If not, destroy it.

    Note that the constructor of objectTwo is now exactly equal to the standard Object constructor function - useless.

    objectTwo.constructor === Object; // true
    

    So calling new objectTwo.constructor() is equivalent to new Object().

提交回复
热议问题