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(', ');
}
-
第一次
my.toString
,此时this.constructor.uber.toString = Triangle.uber.toString = TwoDShape.prototype.toString
-
这时候调用的就是
TwoDShape.toString
了,同样再走一遍流程,此时this.constructor.uber.toString = TwoDShape.uber.toString = Shape.prototype.toString
这时候调用的就是
Shape.toString
了,因为Shape.uber
不存在,所以if
就直接跳过了,执行后面的result[ reult.length ] = this.name
并返回结果,也就是shape
。跳回
TwoDShape.toString
,此时条件语句就定义了result[0] = 'shape'
,然后后面就定义了result[1] = '2D shape'
,所以TwoShape.toString
返回的就是shape, 2D shape
。跳回
Triangle.toString
,根据上一条我们知道条件语句返回的就是result[0] = 'shape, 2D shape'
,然后后面定义了result[1] = 'Triangle'
,所以my.toString
返回的就是shape, 2D shape, Triangle
。