What it the significance of the Javascript constructor property?

前端 未结 6 929
一生所求
一生所求 2020-11-22 04:23

Trying to bend by head around Javascript\'s take on OO...and, like many others, running into confusion about the constructor property. In particular, the signif

6条回答
  •  一向
    一向 (楼主)
    2020-11-22 04:55

    One of the use cases when you would want the prototype.constructor property to survive prototype property reassignment is when you define a method on the prototype that produces new instances of the same type as the given instance. Example:

    function Car() { }
    Car.prototype.orderOneLikeThis = function() {  // Clone producing function
        return new this.constructor();
    }
    Car.prototype.advertise = function () {
        console.log("I am a generic car.");
    }
    
    function BMW() { }
    BMW.prototype = Object.create(Car.prototype);
    BMW.prototype.constructor = BMW;              // Resetting the constructor property
    BMW.prototype.advertise = function () {
        console.log("I am BMW with lots of uber features.");
    }
    
    var x5 = new BMW();
    
    var myNewToy = x5.orderOneLikeThis();
    
    myNewToy.advertise(); // => "I am BMW ..." if `BMW.prototype.constructor = BMW;` is not 
                          // commented; "I am a generic car." otherwise.
    

提交回复
热议问题