I
I
Iliaity2015-11-27 08:57:32
JavaScript
Iliaity, 2015-11-27 08:57:32

How does a supertype accessor work?

I'm trying to figure it out with an example. This example overrides the toString method, but the call to rect.toString() does not work. Please tell me why? And how does the rewrite happen here?

function Rectangle(length, width) {
this.length = length;
this.width = width;
}
Rectangle.prototype.getArea = function() {
return this.length * this.width;
};
Rectangle.prototype.toString = function() {
return "[Rectangle " + this.length + "x" + this.height + "]";
};
function Square(size) {
Rectangle.call(this, size, size);
}
Square.prototype = Object.create(Rectangle.prototype, {
constructor: {
configurable: true,
enumerable: true,
value: Square,
writable: true
}
});
// Что происходит в данном коде ??? 
Square.prototype.toString = function() {
var text = Rectangle.prototype.toString.call(this);
return text.replace("Rectangle", "Square");
};
var rect = new Rectangle(5, 10);
var square = new Square(6);

console.log(rect.getArea());
console.log(square.getArea());

console.log(rect.toString()); 
console.log(square.toString());

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
RubaXa, 2015-11-27
@RubaXa

1. It was possible not to override the method: jsbin.com/cifanopojo/edit?js,console
2. call/ apply- this is not “access to the supertype”, but a simple execution of the method in the context
you need 3. If you need a full-fledged superone, go to ES6 / Babel .

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question