【Web前端问题】javascript中的uber怎么用求解释

javascript中的uber怎么用求解释
代码

结果

回答:

uber 只是一个对象属性而已,没有什么特殊的。然后虽然看着哟亣多,但其实这就是一个递归而已。我们先把 toString 的代码抄一下:

Shape.prototype.toString = function() {

var result = [];

if( this.constructor.uber ) {

result[ result.length ] = this.constructor.uber.toString();

}

result[ result.length ] = this.name;

return result.join(', ');

}

  1. 第一次 my.toString ,此时

    this.constructor.uber.toString 

    = Triangle.uber.toString

    = TwoDShape.prototype.toString

  2. 这时候调用的就是 TwoDShape.toString 了,同样再走一遍流程,此时

    this.constructor.uber.toString 

    = TwoDShape.uber.toString

    = Shape.prototype.toString

  3. 这时候调用的就是 Shape.toString 了,因为 Shape.uber 不存在,所以 if 就直接跳过了,执行后面的 result[ reult.length ] = this.name 并返回结果,也就是 shape

  4. 跳回 TwoDShape.toString ,此时条件语句就定义了 result[0] = 'shape',然后后面就定义了 result[1] = '2D shape',所以 TwoShape.toString 返回的就是 shape, 2D shape

  5. 跳回 Triangle.toString,根据上一条我们知道条件语句返回的就是 result[0] = 'shape, 2D shape',然后后面定义了 result[1] = 'Triangle',所以 my.toString 返回的就是 shape, 2D shape, Triangle

以上是 【Web前端问题】javascript中的uber怎么用求解释 的全部内容, 来源链接: utcz.com/a/140371.html

回到顶部