javascript - Why do you reset an objects constructor when a subclass extends superclass? -


question: why example set rectangle.prototype.constructor rectangle when subclass extends superclass? best practice? illustrate gets reset? because example works regardless.

            function shape() {               this.x = 0;               this.y = 0;             }              // superclass method             shape.prototype.move = function(x, y) {               this.x += x;               this.y += y;               console.info('shape moved.');             };              // rectangle - subclass             function rectangle() {               shape.call(this); // call super constructor.             }              // subclass extends superclass              rectangle.prototype = object.create(shape.prototype);             rectangle.prototype.constructor = rectangle;              var rect = new rectangle();             console.log(rect);             console.log('is rect instance of rectangle? ' + (rect instanceof rectangle)); // true             console.log('is rect instance of shape? ' + (rect instanceof shape)); // true             rect.move(1, 1); // outputs, 'shape moved. 

when rectangle.prototype = object.create(shape.prototype); run, default set constructor of rectangle shape.prototype.constructor - not want. have go ahead , explicitly set rectangle.prototype.constructor rectangle constructor function, new objects rectangle objects. paste code here: http://www.objectplayground.com/, select "classical inheritance", , change "rect" " this.instance = new rectangle();". play around it, comment out line , see difference makes.

hope makes sense!


Comments

Popular posts from this blog

c - Bitwise operation with (signed) enum value -

xslt - Unnest parent nodes by child node -

YouTubePlayerFragment cannot be cast to android.support.v4.app.Fragment -