Why is it necessary to set the prototype constructor?

前端 未结 14 1763
孤城傲影
孤城傲影 2020-11-22 02:54

In the section about inheritance in the MDN article Introduction to Object Oriented Javascript, I noticed they set the prototype.constructor:

// correct the          


        
14条回答
  •  时光说笑
    2020-11-22 03:10

    Got a nice code example of why it is really necessary to set the prototype constructor..

    function CarFactory(name){ 
       this.name=name;  
    } 
    CarFactory.prototype.CreateNewCar = function(){ 
        return new this.constructor("New Car "+ this.name); 
    } 
    CarFactory.prototype.toString=function(){ 
        return 'Car Factory ' + this.name;
    } 
    
    AudiFactory.prototype = new CarFactory();      // Here's where the inheritance occurs 
    AudiFactory.prototype.constructor=AudiFactory;       // Otherwise instances of Audi would have a constructor of Car 
    
    function AudiFactory(name){ 
        this.name=name;
    } 
    
    AudiFactory.prototype.toString=function(){ 
        return 'Audi Factory ' + this.name;
    } 
    
    var myAudiFactory = new AudiFactory('');
      alert('Hay your new ' + myAudiFactory + ' is ready.. Start Producing new audi cars !!! ');            
    
    var newCar =  myAudiFactory.CreateNewCar(); // calls a method inherited from CarFactory 
    alert(newCar); 
    
    /*
    Without resetting prototype constructor back to instance, new cars will not come from New Audi factory, Instead it will come from car factory ( base class )..   Dont we want our new car from Audi factory ???? 
    */
    

提交回复
热议问题