0
        function Shape(){}
            Shape.prototype.name='Shape';
            Shape.prototype.toString=function(){
                var result=[];
                if(this.constructor.uber){
                    console.log(this.constructor);
                    //TwoDShape 也执行了一次toString()方法
                    result[result.length]=this.constructor.uber.toString();            
                }    
                result[result.length]=this.name;
                return result.join(', ')
            }
            
            function TwoDShape(){}
            var F=function(){};
            F.prototype=Shape.prototype;
            TwoDShape.prototype=new F();
            TwoDShape.prototype.constructor=TwoDShape;
            TwoDShape.uber=Shape.prototype;
            TwoDShape.prototype.name='2D Shape';
            
            function Triangle(side,height){
                this.side=side;
                this.height=height 
            }
            var F=function(){};
            F.prototype=TwoDShape.prototype;
            Triangle.prototype=new F();
            Triangle.prototype.constructor=Triangle;
            Triangle.uber=TwoDShape.prototype;
            Triangle.prototype.name='triangle';
            Triangle.prototype.getArea=function(){
                return this.side*this.height/2;
            }
            var my =new Triangle(5,10);
            console.log(my.toString());

为什么Triangle也会执行一次toString()方法,我对这个流程不太清楚,麻烦帮我梳理一下。
主要是那个被重写的toString()里面执行下来不太明白。

1个回答

0

已采纳

知识点就是原型链继承 + 函数递归
首先,在整个原型链上toString()只在Shape的原型上被覆写,整个过程用的也只有这个函数;
其次,toString()有his.constructor.uber.toString()明显是个递归,toString()被调用三次依次如下:
my.toString() => TwoDShape.prototype.toString() => Shape.prototype.toString()
递归前的代码正序执行: Triangle => TwoDshape
递归后的代码倒序执行:triangle <= 2D Shape <= Shape

撰写答案