JavaScript面向对象精要(下部)(2)

function Rect(length,width){ this.length = length; this.width = width; } Rect.prototype.getArea = function(){ return this.width * this.length; }; Rect.prototype.toString = function(){ return "[Rect"+this.length+"*"+this.width+"]"; }; function Square(size){ this.length = size; this.width = size; } //修改prototype属性 Square.prototype = new Rect(); Square.prototype.constructor = Square; Square.prototype.toString = function(){ return "[Square"+this.length+"*"+this.width+"]"; }; var rect = new Rect(5,10); var square = new Square(6); console.log(rect.getArea()); //50 console.log(square.getArea()); //36

如果要访问父类的toString(),可以这样做:

Square.prototype.toString = function(){ var text = Rect.prototype.toString.call(this); return text.replace("Rect","Square"); }

您可能感兴趣的文章:

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wygwwd.html